What is the difference between Future.delayed vs Timer in flutter

Timer:

Timer() creates a Timer object, that runs your computation after a delay. Since you get the reference to that Timer object, you can choose to cancel it before it's fired, by calling cancel.

Timer t = Timer(Duration(seconds: 1), () => print("1 sec later"));
t.cancel(); // nothing will be printed out

Future:

Future.delayed creates a Future that runs its computation after a delay. Internally, it's still using a Timer to do that. It does not expose the timer to you, so you cannot control or cancel it. On the bright side, you get to do your normal Future stuff, like await on it.

await Future.delayed(Duration(seconds: 1);
print("1 sec later");

Use Timer if:

  • You want the ability to cancel it. With Timer.cancel() you cancel the timer unlike Future where you'll have to make use of CancelableCompleter to cancel the Future.

  • If you don't want to return anything in your callback method.

    Example:

    // Prints 'Hello' after 1s. 
    var timer = Timer(Duration(seconds: 1), () => print('Hello'));
    

    And in case you decide to cancel it, use:

    timer.cancel();
    

Use Future if:

  • Your code can throw errors and you want to catch them. Had you used Timer and any uncaught exceptions occurs, the app will exit.

  • You want to return something from your callback method.

    Example:

    // Return 'Hello' after 1s and if there is any error, it will be caught. 
    Future
      .delayed(Duration(seconds: 1), () => 'Hello')
      .catchError((err) {}); 
    

A couple of differences for me.

  • Future.of returns a Future.
  • Timer does not return anything.

So if your delayed code returns anything that you need to continue your working, Future is the way to go.


Other difference is that the Timer class provides a way to fire repeatedly.

This quote is from the Timer Class Reference documentation itself

A count-down timer that can be configured to fire once or repeatedly

And example to use Timer with the repeat could be

Timer.periodic(Duration(seconds: 5), (timer) {
    print(DateTime.now()); 
});

Other frecuent example is to create a stopwatch, to measure timings in your code, it's usually seen using a Timer.

GL!!