如何在Flutter中设置时间间隔?

45

最近我在Flutter中尝试创建一个时间间隔,但是我没有看到类似于JavaScript中的setInterval(function(){}, 1000)。在Flutter中是否存在相似的功能?


1
这是你想要的吗?https://docs.flutter.io/flutter/dart-async/Timer-class.html - ADM
无需在问题标题中重复。 - takendarkk
上面的链接无法打开(404错误)。新链接:https://api.flutter.dev/flutter/dart-async/Timer-class.html - Japsimrans13
1个回答

113

你可以使用计时器来实现。

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

编辑过的内容

正如@MoeinPorkamel在评论中指出的那样,上面的答案更像是setTimeout而不是setInterval!需要间隔执行的人可以使用以下代码:

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

要使用 Timer,您需要 import 'dart:async';


6
请注意,使用计时器需要导入async: import 'dart:async'; - Mans
10
这更像是setTimeout而不是interval!需要interval的人可以使用Timer.periodic - MoeinPorkamel
@MoeinPorkamel,感谢你指出正确的答案。为什么不把你的评论变成单独的答案呢,这样它就可以被点赞(和接受)作为正确的答案,而不是这个? - atsu85
1
我该如何使用它来定期更改Flutter中UI的状态? - HexaCrop
1
@tinyCoder Timer.periodic(new Duration(seconds: 1), (timer) { timer.cancel(); }); - Ajay Kumar
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接