Event Queues and Microtask Queues

This would be the case if you were invoking methods without calling .then

A way to add a task to the microtask queue is to invoke then() on a Future that’s already complete.

So when you call myFunction().then(print); future is added to microtask queue.

Some bonus facts for the cases when calling without '.then': According to the docs there were 2 bugs. These bugs were fixed, but the issue still remains :(

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()


Notes for the general reader:

  • The Event Loop has two queues of tasks: the Microtask Queue and the Event Queue.
  • Any tasks in the Microtask Queue are always run before the next task in the Event Queue.
  • Microtasks are generally scheduled by the system while Event Queue tasks generally come from the outside events (IO, app events, etc.).

I believe the following points explain the behavior that you are observing:

  • The Future.value() constructor schedules a microtask on the Microtask Queue.

  • The Future() constructor, on the other hand, schedules a regular task on the Event Queue.

The original link you shared is only available as an archive now:

  • The Event Loop and Dart

It is still worth reading, though.

Tags:

Dart

Flutter