Back to results for “Threading”
Flutter › Dart Asynchronous Programming (Future & async/await)

What is the difference between microtasks and the event queue in Dart's event loop, and how does this affect the precise order in which asynchronous code actually executes?

Intermediate

Answer

Dart's single threaded event loop processes two distinct internal queues, the microtask queue and the event queue, with the microtask queue always being fully drained first before Dart moves on to processing the next item in the event queue, and understanding this distinction matters because scheduling something using Future.microtask executes it sooner, before other queued events like timers or genuinely completed I/O operations, than scheduling the exact same work using something like Future.delayed, which places its work specifically into the later processed event queue instead.
print('1');
Future.microtask(() => print('2'));
Future(() => print('3'));
print('4');
// Actual output order: 1, 4, 2, 3
Real-world example A developer debugging an unexpected ordering issue in their asynchronous code discovers that a Future.microtask callback consistently runs before a regular Future callback, and adjusts their code's logic after properly understanding this specific underlying event loop execution order.

Common follow-ups: Why does understanding this event loop ordering rarely matter for most typical everyday application code?;How does this same underlying event loop relate to how Flutter actually schedules and renders each individual UI frame?