CodeBlanks Logo Icon CodeBlanks

Event loop

Learn the Dart event loop model.

What is the event loop?

Dart is a single-threaded language; all code runs inside one event loop. The loop takes one task at a time, runs it to completion, then moves on.

There are two queues: the event queue (Future, I/O, timers) and the microtask queue (higher priority). Each turn drains all microtasks first, then runs one event.

Therefore long synchronous code blocks the event loop. CPU-heavy work goes to an Isolate; I/O waiting goes to a Future.

Observing the event loop

A Future, when completed, adds a task to the event queue. With await main suspends until that task is processed.

Example: print('a'); await Future.delayed(Duration(milliseconds: 1)); print('b');. 'a' prints immediately, then a 1 ms event is awaited, then 'b' prints.

This ordering is deterministic: since the event loop is single-threaded, the output is always the same.

Practice Observe the event loop order

Make main async. Add print('a'), then await Future.delayed(Duration(milliseconds: 1)), then print('b').

Starter code

main.dart
void main() {
  // make async; print 'a'; wait 1 ms; print 'b'
}

Sample solution

main.dart
void main() async {
  print('a');
  await Future.delayed(Duration(milliseconds: 1));
  print('b');
}

Expected output

a
b

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which statement about the event loop is true?

  • Multiple threads run in parallel
  • Microtasks run after events
  • Microtasks run before events Correct answer
  • Synchronous code does not block the loop

Explanation: each turn drains all microtasks first, then runs one event.

2 Event loop queues

Question
First ____ queue, then the event queue is processed.
Answer
First microtask queue, then the event queue is processed.

Explanation: the microtask queue has priority.

3 Match the loop parts

Term Meaning
Event loop Single thread
Event queue Future / I/O
Microtask Priority task
await Suspension point

All lessons in Advanced