Microtasks
- Dart course
- Advanced
- Lesson 8/83
- 5 min
Learn the microtask and macrotask queues.
The microtask queue
A microtask is a small task that runs before events in each event-loop turn. It is scheduled with Future.microtask or scheduleMicrotask.
Usage: small, synchronous, urgent work. For example notifying a stream listener. Long work must not go in a microtask; it blocks the loop.
Example: await Future.microtask(() => print('first')). The microtask runs and completes, then execution continues.
await Future.microtask
Future.microtask(fn) schedules fn as a microtask and returns a Future that completes with its result. With await the flow suspends until the microtask is processed.
This is useful for squeezing small synchronous work before events. Example: await Future.microtask(() => 42) — the microtask produces 42, await yields 42.
Note: putting long computation in a microtask blocks the event loop; avoid I/O and heavy CPU.
Practice Observe microtask ordering
Make main async. Add print('a'). Add await Future.microtask(() => print('b')). Finally add print('c').
Starter code
void main() {
// make async; print 'a'; microtask prints 'b'; print 'c'
}Sample solution
void main() async {
print('a');
await Future.microtask(() => print('b'));
print('c');
}Expected output
a b c
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Schedule a microtask
await Future.____(() => print('first'));
await Future.microtask(() => print('first'));
Explanation: Future.microtask schedules a microtask.
2 When is a microtask processed?
- Only with await
- After events, in the next turn
- Only inside an Isolate
- Before events, in the same turn Correct answer
Explanation: microtasks are processed before events in the same turn.
3 Microtask parts
| Term | Meaning |
|---|---|
Future.microtask |
Microtask constructor |
scheduleMicrotask |
Top-level function |
microtask queue |
Priority queue |
await |
Suspension |