问题描述
我想知道Future.delayed和Timer方法之间的区别,以延迟代码执行.两者似乎都做同样的事情.
I like to know the differences between Future.delayed and Timer method for delaying code execution. Both seem to do the same thing.
未来延迟
Future.delayed(const Duration(milliseconds: 500), () { /*code*/ });
VS
计时器
Timer _timer = new Timer(const Duration(milliseconds: 500), () { /*code*/ });
推荐答案
对我来说有一些区别.
-
Future.of
返回一个Future. -
计时器
不返回任何内容.
Future.of
returns a Future.Timer
does not return anything.
因此,如果您的延迟代码返回了继续工作所需的任何内容,那么 Future
是您的理想选择.
So if your delayed code returns anything that you need to continue your working, Future
is the way to go.
其他区别是 Timer
类提供了一种重复触发的方法.
Other difference is that the Timer
class provides a way to fire repeatedly.
此引用来自计时器类参考文档本身
将 Timer
与 repeat 结合使用的示例可能是
And example to use Timer
with the repeat could be
Timer.periodic(Duration(seconds: 5), (timer) {
print(DateTime.now());
});
另一个出色的示例是创建一个秒表,以测量代码中的计时,通常使用 Timer
来查看.
Other frecuent example is to create a stopwatch, to measure timings in your code, it's usually seen using a Timer
.
GL !!
这篇关于Flutter中Future.delayed与Timer之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!