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

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
}


Solution 1:[1]

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);

Solution 2:[2]

The current API does not provide to change it's behavior. But you can extract that inline function and call it yourself after starting the timer.

final timer = Timer.periodic(durationBetweenPayoutIterations, myCallback);
myCallback(timer);

myCallback(Timer timer) async {
  // Code to be executed
}

Solution 3:[3]

You can use a trick-method like this:

void _startTimerPeriodic(int millisec) {
    Timer.periodic(Duration(milliseconds: millisec), (Timer timer) async {
      // Your code here;

      if (millisec == 0) {
        timer.cancel();
        _startTimerPeriodic(1000 * 60 * 2);
      }
    });
  }

then call it the first time as:

_startTimerPeriodic(0);

Solution 4:[4]

you can do this.

import 'dart:async';
 Timer? timer;

  @override
  initState() {
    timer = Timer.periodic(const Duration(milliseconds: 500), ((timer) {
      getData();
    }));
    super.initState();
  }

  @override
  dispose() {
    timer!.cancel();
    super.dispose();
  }

  Future<void> getData() async {}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jamesdlin
Solution 2 Amir_P
Solution 3 G3nt_M3caj
Solution 4 germain kataku