How to toggle on and off an animation with the same key?

So, basically I am trying to use the Key F to make my character do an animation to point a flashlight, but I am having a problem, when using the animator the transitions bug. Ive made a script for it to do the animation when I press the F key, but I cant use the same aproach to toggle off the animation (or turning off the flashlight). Only worked if I used other key like the E key so it wouldnt conflict.

Here’s the script:

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using UnityEngine;
using Debug = UnityEngine.Debug;

public class PlayerWalk : MonoBehaviour
{
    private Animator anim;

    private float walk = 0.0f;

    private float mSpeed = 3f;

    public float rotation = 100;

    public bool flash = false;


    void Start()
    {
        anim = GetComponent<Animator>();

        anim.SetInteger("Flash", 0);

    }


    void Update()
    {
        transform.Translate(mSpeed * Input.GetAxis("Horizontal") * Time.deltaTime, 0.0f, mSpeed * Input.GetAxis("Vertical") * Time.deltaTime);

        walk = Input.GetAxis("Vertical");

        if (Input.GetKey(KeyCode.LeftShift))
        {
            walk += 1;

            mSpeed = 10f;

        if (Input.GetKeyUp(KeyCode.LeftShift))
        {
            walk = 1;

            mSpeed = 3f;
        }

        if (Input.GetKeyDown(KeyCode.F))
        {
            anim.SetInteger("Flash", 1);
            flash = true;
            //walk = 5;

        }

        if (Input.GetKey(KeyCode.F) && (flash == true))
        {

            anim.SetInteger("Flash", 0);
            //walk = 5;

        }
       
        if (Input.GetKey(KeyCode.S))
        {
            walk = -1;
        }

        anim.SetFloat("Walk", walk);

        this.transform.Rotate(0, (Input.GetAxis("Horizontal") * rotation) * Time.deltaTime, 0);

    }
}

Hi!
Try replacing lines 49-63 with the following code:

    if (Input.GetKeyDown(KeyCode.F))
    {
             if (flash == false)
             {
                      anim.SetInteger("Flash", 1);
                      flash = true;
             }
             else
             {
                      anim.SetInteger("Flash", 0);
                      flash = false;
             }
    }