Zone
- Dart course
- Advanced
- Lesson 11/83
- 5 min
Learn context management with Zone.
What is a Zone?
A Zone is Dart's execution environment abstraction. Every Future, microtask and callback runs inside a Zone. The default is Zone.root.
Zone.fork creates a child zone. Child zones are used to add error handling, task interception and custom behavior.
Example: runZoned(() => ...) runs the body in a new zone. Errors thrown inside go to the zone's error handler.
Error handling with Zones
If you pass onError to runZoned, uncaught errors thrown inside the body go to this handler. This is the core mechanism for global error handling in async code.
Example: runZoned(() { throw 'hop'; }, onError: (e, s) => print('error: $e'));. The body throws, onError is called, the program does not crash.
Without a zone, an uncaught error inside a Future terminates the program. Wrapping async code in a zone is therefore good practice.
Practice Run a body with runZoned
Inside main add a call runZoned(() { print('zone içi'); });. Then add print('dış');.
Starter code
void main() {
// run a body with runZoned; then print 'dış'
}Sample solution
void main() {
runZoned(() {
print('zone içi');
});
print('dış');
}Expected output
zone içi dış
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Start a new zone
____(() { print('in zone'); });
runZoned(() { print('in zone'); });
Explanation: runZoned runs the body in a new zone.
2 Zone concepts
| Term | Meaning |
|---|---|
Zone.root |
Default zone |
Zone.fork |
Child zone |
runZoned |
Body execution |
onError |
Error handler |
3 What does runZoned do?
- Starts a new Isolate
- Stops the event loop
- Runs a body in a new zone Correct answer
- Makes a Future synchronous
Explanation: runZoned runs a body in a new zone.