How to make a Timer.periodic function fire right away after calling it Flutter

856

If you mean that you want a periodic Timer where the initial callback is triggered immediately, you can write a helper function:

Timer makePeriodicTimer(
  Duration duration,
  void Function(Timer timer) callback, {
  bool fireNow = false,
}) {
  var timer = Timer.periodic(duration, callback);
  if (fireNow) {
    callback(timer);
  }
  return timer;
}

and then instead of using Timer.periodic directly, you could do:

var timer = makePeriodicTimer(duration, callback, fireNow: true);
Share:
856
Jack Maring
Author by

Jack Maring

Updated on December 31, 2022

Comments

  • Jack Maring
    Jack Maring over 1 year

    I'm trying to use a Timer.periodic function in flutter and it seems that when I call it, it waits for the specified duration that I put in for the time between callback triggers before actually going into the timer and firing off the code within. So if I put 2 mins for durationBetweenPayoutIterations, it waits 2 mins, then goes into the block and fires the callback every 2 mins.

    How do you make it so that the timer starts right away and the code in the timer block starts executing right when you activate it?

    Timer.periodic(durationBetweenPayoutIterations, (timer) async {
      // Code to be executed
    }