Sub topic 11
runZonedGuarded, legacy code and zone mismatches
This chapter assumes you can read basic Dart, including async/await and Futures. It also assumes you have built a small Flutter app with runApp. You should already know the two handlers from the earlier chapters: FlutterError.onError for framework errors and PlatformDispatcher.instance.onError for uncaught asynchronous errors.
Many tutorials, Stack Overflow answers and older codebases use a third mechanism, runZonedGuarded. This chapter explains what it does, why you will still meet it, and the warning it can cause in Flutter apps. It also covers how to move such code to PlatformDispatcher.instance.onError.
What a zone is
A zone is a Dart object that controls how asynchronous work behaves for the code running inside it. Every Dart program starts in the root zone. Any Future, Timer or microtask you create remembers the zone it was created in. When that work runs later, it runs in the same zone.
A zone can customize several things:
- What happens to an uncaught error.
- What
printdoes. - How timers and microtasks are scheduled.
- Which values are visible to code in the zone, through zone values.
runZonedGuarded creates a child zone and gives it an error handler. Any uncaught asynchronous error from code running in that zone goes to your handler. Without such a handler, it would propagate to the root zone.
import 'dart:async';
void main() {
runZonedGuarded(() {
Future<void>.delayed(const Duration(milliseconds: 10), () {
throw StateError('Nobody catches this');
});
}, (Object error, StackTrace stack) {
print('Zone caught: $error');
});
}The Future is created inside the guarded zone, so the zone's handler receives the StateError. The callback you pass to runZonedGuarded has no return value you need, and the function itself returns the new Zone, or null if the body failed synchronously.
Why it was the standard answer
Before PlatformDispatcher.onError existed, Flutter had no official hook for uncaught asynchronous errors. The only way to see them was to run the whole app inside a guarded zone. The documented pattern looked like this:
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
runZonedGuarded(() {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details);
debugPrint('Framework error: ${details.exceptionAsString()}');
};
runApp(const MyApp());
}, (Object error, StackTrace stack) {
debugPrint('Zone error: $error\n$stack');
});
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: Scaffold(body: Center(child: Text('Hello'))));
}
}This version works because everything, including ensureInitialized, happens inside the zone. Many crash-reporting SDK guides were written this way, and you will find the pattern in older projects.
Why it is no longer the primary mechanism
Zones have three drawbacks in Flutter.
- They only see work created in the zone. An error from a Future or Timer created outside the zone never reaches the zone handler. This includes plugin callbacks and code that runs before your
runZonedGuardedcall. - Using them correctly is easy to get wrong. The binding and
runAppmust be in the same zone. Getting this wrong causes the zone mismatch warning described below. - They are no longer necessary.
PlatformDispatcher.instance.onErrorsits at the root. It receives uncaught asynchronous errors without any zone setup, and its boolean return value lets you say whether you handled the error.
The current approach from the earlier chapters is a flat main() with no zone:
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('Uncaught async error: $error\n$stack');
return true;
};
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: Scaffold(body: Center(child: Text('Hello'))));
}
}Where an asynchronous error goes
The path an error takes depends on the zone its Future was created in.
The consequence is that if you use both mechanisms, errors split between two handlers. Your reporting code then has to be wired into both, or some errors go unreported. Using only one mechanism avoids this.
Zone mismatches
A zone mismatch happens when the Flutter binding is initialized in one zone and runApp is called in another. The most common cause is this code:
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized(); // root zone
runZonedGuarded(() {
runApp(const MyApp()); // child zone
}, (Object error, StackTrace stack) {
debugPrint('Zone error: $error');
});
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: Scaffold(body: Center(child: Text('Hello'))));
}
}In debug mode, Flutter prints a message that begins with "Zone mismatch". It warns that the bindings were initialized in a different zone than the one now in use. It also warns that zone-specific configuration may not behave as you expect.
The problem is not cosmetic. The engine calls into the framework through callbacks, such as frame and pointer callbacks. Those callbacks run in the zone that was active when the binding registered them. If the binding was set up in the root zone, those callbacks run there. Your guarded zone then sees only part of the app's activity. Zone values and print overrides you set up for the guarded zone are skipped for the rest.
Calling ensureInitialized in one zone and runApp in another can also hide errors from your handler. You may believe the app is fully guarded when it is only partly guarded.
Fixing a mismatch
You have two options.
- Keep the zone and move everything inside it. Put
WidgetsFlutterBinding.ensureInitialized()andrunAppin the same callback. This is the layout shown earlier in the legacy pattern. - Drop the zone. Install
PlatformDispatcher.instance.onErrorand callrunAppdirectly. This is usually the better choice for new and migrated code.
Migrating legacy code
Migrating is a mechanical change. Use these steps:
- Move
WidgetsFlutterBinding.ensureInitialized()to the first line ofmain(), outside any zone. - Copy the body of the
runZonedGuardederror callback into a function with the signaturebool Function(Object, StackTrace). - Return
truefrom that function if you reported the error and do not want the engine to report it again. - Assign the function to
PlatformDispatcher.instance.onError. - Replace the
runZonedGuardedcall with a plainrunApp(...). - Run the app and trigger a failing Future to confirm the new handler fires.
The reporter class from the earlier chapter makes this easy. The handler you pass to a zone and the one you assign to PlatformDispatcher need different return types, which is the only adjustment:
import 'dart:async';
import 'dart:ui';
import 'package:flutter/foundation.dart';
class ErrorReporter {
static void report(Object error, StackTrace stack) {
// Replace with a call to your logging or crash-reporting service.
debugPrint('error: $error');
debugPrint('stack: $stack');
}
}
// Legacy: a zone handler returns nothing.
void legacyHandler(Object error, StackTrace stack) {
ErrorReporter.report(error, stack);
}
// Current: a PlatformDispatcher handler returns true when handled.
bool modernHandler(Object error, StackTrace stack) {
ErrorReporter.report(error, stack);
return true;
}
void installModernHandler() {
PlatformDispatcher.instance.onError = modernHandler;
}Because both handlers call ErrorReporter.report, you can run old and new code side by side while you migrate one entry point at a time.
Reasons to keep a zone
A zone is still the right tool when you need something other than error handling. Examples include:
- Overriding
printfor the whole app, for example to copy output into a log buffer. - Passing values implicitly to everything created in a scope, using zone values.
- Wrapping timers or microtasks for instrumentation or testing.
If you keep a zone for one of these reasons, put ensureInitialized and runApp inside it. The zone can still hold an error handler. In that case, an async error is reported by whichever handler applies to its zone, as the diagram showed.
import 'dart:async';
import 'package:flutter/material.dart';
final List<String> logBuffer = <String>[];
void main() {
runZonedGuarded(
() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MaterialApp(home: Scaffold(body: Center(child: Text('Hello')))));
print('App started'); // captured by the zone
},
(Object error, StackTrace stack) {
logBuffer.add('error: $error');
},
zoneSpecification: ZoneSpecification(
print: (Zone self, ZoneDelegate parent, Zone zone, String line) {
logBuffer.add(line);
parent.print(zone, line); // still write to the console
},
),
);
}The print override captures lines into logBuffer and also forwards them to the parent zone so the console output stays. Without that forwarding call, the line would vanish.
Comparing the two approaches
| Aspect | `runZonedGuarded` | `PlatformDispatcher.instance.onError` |
|---|---|---|
| Setup | Wrap `ensureInitialized` and `runApp` in a callback | Assign one handler before `runApp` |
| Scope | Work created inside that zone | Errors that reach the root zone uncaught |
| Return value | None | `true` marks the error as handled |
| Common failure | Zone mismatch | Handler that throws or loops |
| Extra abilities | Override `print`, zone values, scheduling | None |
Pitfalls to remember
- Using both mechanisms without a plan can split your errors between two handlers. Pick one for reporting.
- An error thrown inside a zone's error handler is passed to the parent zone. A throwing handler hides the original error, so keep handlers simple and wrap risky reporting calls in
try/catch. - Plugins may create Futures in the root zone. A guarded zone never sees their failures, and
PlatformDispatcher.instance.onErrordoes. - Removing a zone also removes your
printoverride and any zone values. Check for both before you delete one.
Exercise
A teammate's main() calls WidgetsFlutterBinding.ensureInitialized(), then runZonedGuarded(() => runApp(const MyApp()), reportError). Debug builds print a "Zone mismatch" message. Name the cause, and describe two ways to fix it.
Show answer
The binding was initialized in the root zone, but runApp runs in the guarded child zone, so the two zones differ. Fix one: move ensureInitialized() inside the runZonedGuarded callback, so both calls share one zone. Fix two: remove runZonedGuarded, assign PlatformDispatcher.instance.onError (returning true after reporting), and call runApp directly.
Exercise
After migrating to PlatformDispatcher.instance.onError, your app no longer logs lines written with print, which used to be captured by a ZoneSpecification. Why did this change, and what can you do about it?
Show answer
The print override lived in the zone. Removing the zone removed the override. Either keep a zone for the override, with ensureInitialized and runApp inside it, or log through a function such as debugPrint or your own logger instead of overriding print.