scheduleMicrotask
- Dart course
- Advanced
- Lesson 10/83
- 5 min
Learn microtasks with scheduleMicrotask.
The scheduleMicrotask function
scheduleMicrotask(fn) adds fn to the microtask queue. It returns nothing; it guarantees ordering but does not wait for a result.
Unlike Future.microtask, it returns no Future. It is meant for small side-effecting work (printing, state updates).
Example: scheduleMicrotask(() => print('micro'));. Synchronous code continues after this line; the microtask is processed at the end of the turn.
microtask vs event order
In one turn all microtasks are drained first, then a single event is processed. Therefore work added via scheduleMicrotask runs before Future.delayed.
Example: scheduleMicrotask(() => print('m')); print('main'); await Future.delayed(Duration(milliseconds: 1));. Order: 'main' (sync), 'm' (microtask turn), then the delayed event completes.
The output is deterministic: 'main', 'm'.
Practice Observe microtask vs event order
Make main async. Add scheduleMicrotask(() => print('m'));. Add print('ana');. Add await Future.delayed(Duration(milliseconds: 1));.
Starter code
void main() {
// make async; schedule microtask printing 'm'; print 'ana'; wait 1 ms
}Sample solution
void main() async {
scheduleMicrotask(() => print('m'));
print('ana');
await Future.delayed(Duration(milliseconds: 1));
}Expected output
ana m
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does scheduleMicrotask return?
- Future<void>
- Nothing (void) Correct answer
- A value
- Stream
Explanation: scheduleMicrotask returns void, no Future to await.
2 Scheduling functions
| Term | Meaning |
|---|---|
scheduleMicrotask |
Microtask queue |
Future.microtask |
Returns a Future |
Future.delayed |
Event queue |
Future.sync |
Calls immediately |
3 Microtask call
____(() => print('m'));
scheduleMicrotask(() => print('m'));
Explanation: scheduleMicrotask adds to the microtask queue.