【发布时间】:2021-05-26 08:50:48
【问题描述】:
在 Dart 中,
和说有什么区别
Future<void> doStuff() async { ...
和
void doStuff() async { ...
我知道 Future
请注意,这两个函数都使用异步。问题不是“异步函数和非异步函数有什么区别?”或者“您能简要介绍一下 Dart 中的异步编程吗?”
我知道已经有一个几乎相同的问题,但是如果您仔细查看答案,您会发现实际上没有人以明确的方式回答这个问题 - 有什么区别?有什么区别吗?没有区别吗?
详细来说,考虑以下两个函数:
// notice there is no warning about not returning anything
Future<void> futureVoid() async {
await Future.delayed(Duration(seconds: 2), () {
var time = DateTime.now().toString();
print('$time : delay elapsed');
});
}
void nonFutureVoid() async {
await Future.delayed(Duration(seconds: 2), () {
var time = DateTime.now().toString();
print('$time : delay elapsed');
});
}
然后用 onPressed() 函数为的按钮测试它们:
onPressed: () async {
await nonFutureVoid(); // notce that this await *DOES* delay execution of the proceeding lines.
var time = DateTime.now().toString();
print('$time : <-- executed after await statement');
}
日志结果:
flutter: 2021-02-23 21:46:07.436496 : delay elapsed
flutter: 2021-02-23 21:46:07.437278 : <-- executed after await statement
如您所见,它们的行为方式完全相同——等待简单的 void 异步版本。那么区别是什么呢?谢谢。
【问题讨论】:
-
我很确定这是一个与我实际回答的问题相同的问题:What's the difference between returning void vs returning Future<void>?
-
好吧,我不知道有这个问题,谢谢......虽然实际差异在 cmets 中被散列出来并且似乎没有定论,但这并不是最大的。
-
你不能等待虚空,你可以等待未来
这就是区别。 -
@NerdyBunz 嗯?答案中解释了差异:调用者不能等待异步
void函数完成。时期。这没有什么不确定的。 -
我预计评论会被删除。 :D
标签: flutter dart asynchronous future