在 Dart 文档中 The Event Loop and Dart (2013)它提到任何 Future
都被添加到 Event
队列中。
它还提到 Microtask
队列总是首先运行,然后是 Event
队列。
这个文档很旧,而且似乎面向 Web 开发,所以我不确定这对于 Flutter 是否与我编写此代码时不同。
Future<String> myFunction() => new Future.value('Hello');
Future<String> myFunction2() => new Future.value('Hello2');
Future<void> mainTest() async {
debugPrint("Sync1");
myFunction().then(debugPrint);
scheduleMicrotask(() { debugPrint("Microtask"); });
myFunction2().then(debugPrint);
debugPrint("Sync2");
}
我得到了
的输出I/flutter ( 6731): Sync1
I/flutter ( 6731): Sync2
I/flutter ( 6731): Hello
I/flutter ( 6731): Microtask
I/flutter ( 6731): Hello2
但如果所有的 Microtask 都应该在下一个 Event 循环之前运行,不应该是这样吗?
I/flutter ( 6731): Sync1
I/flutter ( 6731): Sync2
I/flutter ( 6731): Microtask // This running first before the Futures?
I/flutter ( 6731): Hello
I/flutter ( 6731): Hello2
最佳答案
如果您在调用方法而不调用 .then
A way to add a task to the microtask queue is to invoke then() on a Future that’s already complete.
所以当你调用 myFunction().then(print);
future 会被添加到微任务队列中。
在没有 '.then
' 的情况下调用时的一些额外事实:
根据docs有 2 个错误。 这些错误已修复,但问题仍然存在 :(
The upshot of these bugs: The first task that you schedule with scheduleMicrotask() seems like it’s on the event queue.
A workaround is to put your first call to scheduleMicrotask() before your first call to new Future()
https://stackoverflow.com/questions/54180637/
相关文章:
android - 如何在 Flutter 中删除 Firebase 云消息传递 token
dart - Flutter ThemeData 不适用于文本
dart - flutter ListView 滚动到索引不可用
dart - 如何在 Dart 中发出网络请求并返回一个 json 对象
amazon-web-services - 在 Flutter 中从 AWS S3 上传和获取媒体文
android - Flutter:构建 APK 时如何传递 Gradle 参数?
dart - Flutter - 如何在 flutter 的数字键盘中添加完成按钮