qdbp
qdbp

Reputation: 11

Flutter wait until bool is true

I really dont find any answers to my problem. I want to execute code when a boolean is true.

I think this is what explains the situation best:


This is what works kinda wrong, since the Timer is executed all the time:

@override
  initState() {
    super.initState();
    Timer.periodic(const Duration(milliseconds: 3000), (timer) { setState((){}); });
  }

What I want is, that the Timer executes after the bool "isIPAdressSet" is true. I thought of something like that, but it gives errors:

@override
  initState() {
    super.initState();
    _updateMethod();
  }

  Future<Timer> _updateMethod() async {
    
    await isIPAddressSet == true; //'await' applied to 'bool', which is not a 'Future'
    
    return Timer.periodic(const Duration(milliseconds: 3000), (timer) { setState((){}); });
  }

Also, if the solution is something completely different, from what i thought, thats fine as well.

Upvotes: 1

Views: 1225

Answers (3)

Ali Bakhtiyari
Ali Bakhtiyari

Reputation: 332

The solution depends on where you're storing and updating the isIpAddressSet value. if it's in your stateful widget, you have to write a setter function, check for the 'true' value there, and start your timer based on that.

But if it's outside of your widget, You need to listen to it using for example ValueNotifier mentioned in another answer.

void updateIsIPAddressSet(bool newValue){
isIPAddressSet = newValue;
if(newValue) startTimerMethod();
}

Upvotes: 0

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63569

You can use ValueNotifier for this case.

  late final ValueNotifier<bool> notifier = ValueNotifier(false)
    ..addListener(() {
      // if value is true
      if (notifier.value) {
        debugPrint("value is true here, perform any operation");
      }
    });

Or using ValueListenableBuilder inside widget.

ValueListenableBuilder<bool>(
  valueListenable: notifier,
  builder: (context, value, child) {
    if (value == true)
      return Text("I am true:)");
    else
      return SizedBox(); // it can return null 
  },
),

To change value use

notifier.value = true;

More about ValueNotifier

Upvotes: 1

Mohamed Fayez
Mohamed Fayez

Reputation: 48

You can try this:

@override
  initState() {
    super.initState();
    if (isIPAddressSet) {
      Timer.periodic(const Duration(milliseconds: 3000), (timer) { setState((){}); });
    }
  }

Upvotes: 1

Related Questions