What is the difference in calling Future and Future.microtask in Flutter?


From the documentation for the Future.microtask constructor, it says:

   * Creates a future containing the result of calling [computation]
   * asynchronously with [scheduleMicrotask].

and the documentation for the regular Future constructor states:

   * Creates a future containing the result of calling [computation]
   * asynchronously with [Timer.run].

I am wondering, what kind of implications do they have on coding, and when should we use one or another?


All microtasks are executed before any other Futures/Timers.

This means that you will want to schedule a microtask when you want to complete a small computation asynchronously as soon as possible.

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'));

You can run this example on DartPad.

The event loop will simply pick up all microtasks in a FIFO fashion before other futures. A microtask queue is created when you schedule microtasks and that queue is executed before other futures (event queue).

There is an outdated archived article for The Event Loop and Dart, which covers the event queue and microtask queue here.

You can also learn more about microtasks with this helpful resource.

Answered By – creativecreatorormaybenot

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *