Search code examples
flutterdartmobiletimerboolean

How can i acces this boolean in this timer?


 GestureDetector(
            onTap: () {
              Timer(Duration(seconds: 10), () {
                bool check =true;
              });
              if (check == true) {
              int details = -10;

I want to acces the boolean check in the timer in the if statement.


Solution

  • You have a scope problem, as you are instantiating the check variable in the function inside the Timer callback, and it will not be accessible outside of that scope.

    You can either have that variable declared in your class and access it when you need it, like this:

    In the class

    bool check;
    int details;
    

    GestureDetector(
      onTap: () {
        Timer(Duration(seconds: 10), () {
          setState((){
            check = true;
            details = -10;
          });
        });
      }
    )
    

    Or, if you don't need the check variable outside that scope, you can just remove it completely:

    In the class:

    int details;
    

    In the Widget:

    GestureDetector(
      onTap: () {
        Timer(Duration(seconds: 10), () {
          setState((){
            details = -10;
          });
        });
      }
    )
    

    I've added setStates in both examples as it seems like you will be updating your view with these values, and it wouldn't work without a setState.