Sub topic 11
runZonedGuarded, legacy code, and zone mismatches
Assume you know Dart async and await, Future, try/catch, and how runApp starts a Flutter application. This chapter explains where runZonedGuarded fits when your app already uses it, and why it should not replace Flutter's two primary error handlers.
What a zone does
A Dart zone is an execution context. It can carry values and replace selected runtime behavior, such as printing, timers, or handling uncaught asynchronous errors. A callback scheduled in a zone normally keeps that zone when it runs later.
runZonedGuarded creates a child zone and runs a function inside it. Its second argument receives an uncaught error from asynchronous work created in that zone:
import 'dart:async';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details);
debugPrint('Framework error: ${details.exceptionAsString()}');
};
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
debugPrint('Platform error: $error');
debugPrint('$stack');
return true;
};
runZonedGuarded<void>(
() {
runApp(const MyApp());
Future<void>.delayed(const Duration(seconds: 1), () {
throw StateError('Failure inside the application zone');
});
},
(Object error, StackTrace stack) {
debugPrint('Zone error: $error');
debugPrint('$stack');
},
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(child: Text('Zone example')),
),
);
}
}The delayed callback inherits the zone created by runZonedGuarded, so its uncaught error reaches the zone error callback. It may never reach PlatformDispatcher.instance.onError. This is one reason a zone handler can make error behavior difficult to predict.
Why it is not the primary Flutter mechanism
Flutter separates errors caught by the framework from errors that escape as uncaught asynchronous errors.
| Error path | Primary handler | Useful information |
|---|---|---|
| Build, layout, paint, and framework callbacks | `FlutterError.onError` | `FlutterErrorDetails` |
| Uncaught asynchronous errors outside the framework | `PlatformDispatcher.instance.onError` | Error object and `StackTrace` |
| Legacy zone-based asynchronous handling | `runZonedGuarded` | Error object and `StackTrace` |
Install the Flutter handlers in main() and use a zone only when you have a specific compatibility or instrumentation need. A zone can still help an older library that expects zone-local values, or code that needs to intercept errors created inside a known zone. It should not be your only crash-reporting path.
The current pattern is:
- Initialize the binding.
- Install
FlutterError.onError. - Install
PlatformDispatcher.instance.onError. - Start the app.
- Add
runZonedGuardedonly around code that deliberately needs it.
Zone mismatches
A zone mismatch occurs when Flutter initializes in one zone but later runs application code in another. For example:
void main() {
WidgetsFlutterBinding.ensureInitialized();
runZonedGuarded<void>(
() {
runApp(const MyApp());
},
(Object error, StackTrace stack) {
debugPrint('Zone error: $error');
},
);
}Here, binding initialization occurs before the guarded zone, while runApp occurs inside it. Flutter stores zone-sensitive state during initialization. Later, callbacks may observe a different zone than the one Flutter expects. In debug mode, Flutter can report a zone-mismatch warning or assertion.
Keep binding initialization and runApp in the same zone. If you must use a zone, create it before both operations:
void main() {
runZonedGuarded<void>(
() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
},
(Object error, StackTrace stack) {
debugPrint('Zone error: $error');
},
);
}Even this arrangement does not remove the need for the two Flutter handlers. It only keeps Flutter's initialization and application startup together.
Common mistakes
- Initializing the binding outside a zone and calling
runAppinside it. - Registering only a zone handler and omitting
FlutterError.onError. - Assuming every
Futurebelongs to the zone where it is awaited. The relevant zone is usually the one active when the asynchronous callback is created. - Reporting an error in the handler with code that throws another error, creating an error loop.
- Testing only debug builds. Some framework error presentation behavior differs in release builds.
Exercise
Why should a Flutter app install FlutterError.onError and PlatformDispatcher.instance.onError even when it already uses runZonedGuarded?
Show answer
The two Flutter handlers cover framework errors and uncaught platform-level asynchronous errors. runZonedGuarded only handles uncaught errors created in its zone, so it is not a complete replacement.