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.
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),(){})
param
could be milliseconds
, seconds
, minutes
and so on.value
could be any integer or floating point.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); }); }
Duration
is a dart class responsible for keeping track of the difference between two points based on time.period
variable represents this difference in time that the recurring function will activate after every second.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. .periodic
is a function of the Timer
class that reactivates the callback function after a set interval.Free Resources