How to run a repeating function in flutter

A repeating/recurring function is a function that periodically runs based on a set timer. Flutter is a language based on Google's dart programming language for client-side development. As flutter acts like a wrapper to dart, its recurring function has the same logic and syntax as that of Dart.

Syntax

Firstly, we need to have the following imports in our main file:

import 'dart:async'

After the required import, we need to define the function inside the main() function using the following syntax:

Timer.periodic(Duration(param:value),(){
})
Syntax
  • param could be milliseconds, seconds, minutes and so on.
  • value could be any integer or floating point.

Example

Let's take an example of the recurring function. We'll increment and print a counter after every second:

import 'dart:async';
void main() {
    var x = 0;
    var period = const Duration(seconds:1);
    Timer.periodic(period,(arg){
        x = x + 1;
        print(x);
    });

}

Explanation

  • Line 4: Here, Duration is a dart class responsible for keeping track of the difference between two points based on time.
  • Line 4: The period variable represents this difference in time that the recurring function will activate after every second.
  • Line 5: Here, Timer is a class in dart that keeps track of the time and decreases the count until it reaches zero. When it reaches zero, the callback function activates.
  • Line 5: Here, .periodic is a function of the Timer class that reactivates the callback function after a set interval.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved