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
paramcould bemilliseconds,seconds,minutesand so on.valuecould 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,
Durationis a dart class responsible for keeping track of the difference between two points based on time. - Line 4: The
periodvariable represents this difference in time that the recurring function will activate after every second. - Line 5: Here,
Timeris 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,
.periodicis a function of theTimerclass that reactivates the callback function after a set interval.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved