43

Recently I tried to make an interval in flutter but I didn't see anything like setInterval(function(){}, 1000) in JavaScript. Does it exist in Flutter?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Michael
  • 441
  • 1
  • 4
  • 7

1 Answers1

109

you can use Timer for that.

Timer timer = new Timer(new Duration(seconds: 5), () {
   debugPrint("Print after 5 seconds");
});

EDITED

as pointed by @MoeinPorkamel in comments. Above answer is more like setTimeout instead of setInterval! Those who need interval, you can use:

// runs every 1 second
Timer.periodic(new Duration(seconds: 1), (timer) {
   debugPrint(timer.tick.toString());
});

To use Timer you need to import 'dart:async';

JChen___
  • 3,593
  • 2
  • 20
  • 12
Ajay Kumar
  • 15,250
  • 14
  • 54
  • 53
  • 6
    also keep in mind to use the timer you need to import async: `import 'dart:async';` – Mans Mar 24 '18 at 08:47
  • 10
    this is more like setTimeout instead of interval! Those who need interval, you can use `Timer.periodic` – MoeinPorkamel Oct 11 '18 at 08:23
  • @MoeinPorkamel, thanks for pointing out the correct answer. Why don't you form your comment into separate answer, so that it could be upvoted (and accepted) as correct answer instead of this one? – atsu85 Feb 02 '19 at 20:52
  • 1
    how can i use this to change the state of a ui in flutter periodically? – HexaCrop May 19 '19 at 15:23
  • How do we stop it? – tinyCoder Sep 21 '19 at 16:04
  • @KevinRED just call setState in function – Ajay Kumar Sep 24 '19 at 08:10
  • 1
    @tinyCoder Timer.periodic(new Duration(seconds: 1), (timer) { timer.cancel(); }); – Ajay Kumar Sep 24 '19 at 08:12
  • @AjayKumar both solutions are working, thanks to share. Kindly tell me how can we call a function in Timer.periodic function. I wrote Timer timer = new Timer.periodic(new Duration(seconds: 2), (timer) { // debugPrint("Print after 2 seconds"); increaseCount(); }); But increaseCount function is not being called every 2 seconds. Kindly share your suggestion. Thanks in advance :) – Kamlesh Oct 27 '19 at 09:50
  • @Kamlesh It looks right so maybe the function increaseCount is getting called but you are missing something else like setState e.t.c. – Ajay Kumar Oct 31 '19 at 00:38