How to use Timer in Flutter and Dart

In web applications, we are used to using setTimeout and setInterval functions when we want to execute some action after certain period of time. Some time we want to execute the action only one time and some time we want to execute the action continuously at certain interval. Flutter applications are no different.

In Flutter you accomplish this task by using Timer class. This class is available in dart:async package.

setTimeout in Flutter

When you want to implement functionality equivalent to setTimeout, you will instantiate a new Timer object.

var duration = Duration(seconds: _priceUpdateFrequency);
// Following timer fires one time only.
    Timer(duration, _getNewPrices);

To create Timer, you will create a Duration object where you will specify interval after which you want the action to execute. Second parameter is function that will be executed after set duration. This action will execute only one time.

setInterval in Flutter

If you need certain action to continuously execute after certain duration, then you will need to create periodic timer.

// Following is a periodic timer that fires at fixed
    // interval of time specified by duration parameter.
    Timer.periodic(duration, _periodPriceUpdates);

Periodic timer is created by calling periodic function on Timer class. The parameters for periodic function are same as one time timer with one difference. Second parameter is a callback function and an instance of Timer object is passed to the function. Following code snipper shows example of callback function that I used in my code.

_periodPriceUpdates(Timer timer) {
    if (_getPriceInProgress) {
      return;
    }

    _getPriceInProgress = true;
    //TODO: Add HTTP requests to get prices

    _getPriceInProgress = false;
    _lastUpdateAt = DateTime.now();
    notifyListeners();
  }

You can use instance of Timer object to cancel the timer if needed. All you will need to do is call cancel function.

This is all that you will need to use Timer in your flutter application. I have posted a video that show all this code and concepts in action. Feel free to leave any questions and comments in that video.

Search

Social

Weather

17.9 °C / 64.1 °F

weather conditions Clouds

Monthly Posts

Blog Tags