Dart - How to Schedule a Microtask

In Dart, we can schedule a short action called Microtask to be executed later but before the asynchronous events like Future, Timer or DOM Events. This article gives you example how to schedule a Microtask and how Microtasks are executed.

Microtasks are executed inside Event Loop. They're store in a dedicated queue with FIFO (First In First Out) order. If you don't already understand how Event Loop works, it's better to read our article about Event Loop in Dart.

To schedule a Microtask, call scheduleMicrotask function which is available after adding import 'dart:async';

 scheduleMicrotask(() -> void callback) -> void

This is the usage example.

 scheduleMicrotask(() => print('ABCDE'));

The question is when will a Microtask be executed. Below are some examples that will give you better understanding how Microtasks are executed.

  main() {
    print('Begin');
    scheduleMicrotask(() => print('MT A'));

    new Future.delayed(new Duration(seconds:5),
            () => print('Future 1'));
    new Future(() => print('Future 2'));

    scheduleMicrotask(() => print('MT B'));

    print('End');
  }

The output is:

  Begin
  End
  MT A
  MT B
  Future 2
  Future 1

Below is another example which is more complex than the previous one.

  main() {

    print('Begin');
    scheduleMicrotask(() => print('MT A'));

    new Future(() => print('Future 1A'))
        .then((_) => print('Future 1B'))
        .then((_) {
          print('Future 1C');
          scheduleMicrotask(() => print('MT 1'));
        })
        .then((_) => new Future(
            () => print('Future 1D')))
        .then((_) => print('Future 1E'));

    scheduleMicrotask(() => print('MT B'));

    new Future(() => print('Future 2'));

    scheduleMicrotask(() => print('MT C'));
    print('End');
  }

And here's the output:

  Begin
  Enda
  MT A
  MT B
  MT C
  Future 1A
  Future 1B
  Future 1C
  MT 1
  Future 2
  Future 1D
  Future 1E

As you can see, the Event Loop will execute all items in the Microtask Queue, then it executes only the first item in Event Queue. For example, while executing Future 1A, a new item is added to the Microtask Queue. Instead of executing Future 2, it executes the Microtask first despite the Future being scheduled first.