Flutter 中调用 Future 和 Future.microtask 有什么区别?

Tre*_*ree 7 dart flutter

Future.microtask构造函数的文档中,它说:

   * Creates a future containing the result of calling [computation]
   * asynchronously with [scheduleMicrotask].
Run Code Online (Sandbox Code Playgroud)

常规Future构造函数的文档说明:

   * Creates a future containing the result of calling [computation]
   * asynchronously with [Timer.run].
Run Code Online (Sandbox Code Playgroud)

我想知道,它们对编码有什么样的影响,我们什么时候应该使用一种或另一种?

cre*_*not 19

所有微任务都在任何其他Futures/ Timers之前执行。

这意味着当您想尽快异步完成一个小计算时,您将需要安排一个微任务。

void main() {
  Future(() => print('future 1'));
  Future(() => print('future 2'));
  // Microtasks will be executed before futures.
  Future.microtask(() => print('microtask 1'));
  Future.microtask(() => print('microtask 2'));
}
Run Code Online (Sandbox Code Playgroud)

您可以在 DartPad 上运行此示例

事件循环将在其他未来之前以先进先出的方式简单地选择所有微任务。当您安排微任务时会创建一个微任务队列,并且该队列在其他期货(事件队列)之前执行。


这里是一个过时的存档文章事件循环和飞镖,它涵盖了事件队列microtask队列 这里

您还可以通过这个有用的资源了解有关微任务的更多信息。


小智 9

void main() async{
  print("A");
  await Future((){
    print("B");
    Future(()=>print("C"));
    Future.microtask(()=>print("D"));
    Future(()=>print("E"));
    print("F");
  });
  print("G");
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明