Timer.periodic()
is great to have a function repeatedly execute, but is it possible to have the the timer cancel itself if an arbitrary condition is reached outside the function being executed by the timer?
Creating a restartable timer in Flutter As we saw above, we can cancel Timer by calling the cancel() method.
A periodic timer is one that goes off periodically, notifying the thread (over and over again) that a certain time interval has elapsed. A one-shot timer is one that goes off just once.
You get the timer passed into the callback. You can just call cancel()
on it:
Timer.periodic(const Duration(seconds: 1), (timer) { if(condition) { timer.cancel(); } });
or
Timer timer; startTimer() { timer = Timer.periodic(const Duration(seconds: 1), (timer) { if(condition) { cancelTimer(); } }); } cancelTimer() { timer.cancel(); }
this way the timer can be cancelled independent of a timer event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With