Home > OS >  Flutter wait until bool is true
Flutter wait until bool is true

Time:05-29

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((){}); });
  }

Thanks in advance!

I hope that you understand what I want. I am a flutter beginner, just to be said :) Also, if the solution is something completely different, from what i thought, thats fine as well.

CodePudding user response:

You can try this:

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

CodePudding user response:

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

  • Related