D
Dart LanguageAdvanced50 XP5 min read

How does Dart's event loop work with event queue and microtask queue?

TL;DR: Dart's event loop runs in a single thread: execute sync code → drain microtask queue completely → process one event → drain microtask queue again → process next event. Microtasks always run before the next event.

Full Answer

The Dart runtime runs in a single thread (per isolate). After executing synchronous code, it loops: process all microtasks, then take one event from the event queue, then process all microtasks again, and so on.

  • Synchronous code: runs to completion first
  • Microtask queue: Future.value(), scheduleMicrotask(), then() on completed Future
  • Event queue: I/O callbacks, Timer, new isolate messages, network responses
  • UI updates: Flutter's frame rendering is an event
⚠️

Flooding the microtask queue can block the event queue, preventing UI updates. If you have many sequential .then() chains, consider yielding to the event loop with Future.delayed(Duration.zero).

Interview Tip

💡

This is why Dart is 'single-threaded but not single-tasked'. The event loop interleaving allows responsive apps without multi-threading. UI jank happens when a single task takes > 16ms before yielding.

#event-loop#microtask#event-queue#async#concurrency