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

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.


Here is an another example of how code would run in sequence in terms of how Futures are executed. In the example below, the resulting print statements wouldn't be in alphabetical order.


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


The resulting print statements would end up in the order shown below. Notice how B, F, and G gets printed first, then C, then E. This is because B,F, and G are synchronous. D then gets called before C and E because of it being a microtask.


enter image description here

Post a Comment

Previous Post Next Post

Subscribe Us


Get tutorials, Flutter news and other exclusive content delivered to your inbox. Join 1000+ growth-oriented Flutter developers subscribed to the newsletter

100% value, 0% spam. Unsubscribe anytime