Dart/Flutter – How to create a repeating timer

In this post, we will learn how to create a repeating or periodic timer. This kind of timer is useful when you want to run/execute a block of code repeatedly. (If you are familiar with Javascript, you will find similar concept with setInterval method).

We will use Timer class to implement the repeated timer. This is quite simple, therefore I will share full working code here. If you have any question, kindly comment it below this post.

void main() {
  final duration = Duration(seconds: 1);
  Timer.periodic(duration, (timer) {
    // Stop the timer when it matches a condition
    if (timer.tick >= 10) {
      timer.cancel();
    }

    print('Tick: ${timer.tick}');
  });
}

Tick: 1
Tick: 2
Tick: 3
Tick: 4
Tick: 5
Tick: 6
Tick: 7
Tick: 8
Tick: 9
Tick: 10

If you are looking for mobile/web Software Engineers to build you next projects, please Drop us your request!

Tagged : / /
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x