Skip to content

Create a Repeating(periodic) Timer with Flutter

Flutter, Dart, Timer1 min read

There's a good chance that you'll need to use a Timer in Flutter at some point if you're going to be updating UI elements every x milliseconds. A good example of this would be a stopwatch app. If that's the case you're probably looking for something similar to Javascript's setInterval method. In Flutter(or dart) you need to use the Timer class.

First of all you have to import dart's async package:

1import 'dart:async';

Then to make the Timer repeat you'll need to make it periodic, below is a sample snippet of how this is done:

1Timer timer = Timer.periodic(Duration(milliseconds: 150), (Timer _) {
2 // Update something...

The method above creates the timer, you also need to pass a Duration object for how often you want the timer to fire. In the code above the timer has been set to fire every 150 milliseconds, you could modify this to your liking(1 second/1 minute for example). You'll also want to hold onto the instance of timer you created so you can cancel it later if the user navigates away from the current screen:

2void dispose() {
3 timer?.cancel();
4 super.dispose();

It might be worth adding that you can use the cancel method from anywhere if you need to cancel the repeating timer for some reason - it isn't limited to the dispose method.