Sub topic 3
Triggering errors on purpose to verify both handlers
This chapter assumes you know the handler setup from the previous chapters: WidgetsFlutterBinding.ensureInitialized(), FlutterError.onError, and PlatformDispatcher.instance.onError. You should also be comfortable with Dart Futures and async/await.
Forcing each kind of error
Test each handler with a button that fails in a known way. A synchronous throw inside onPressed is caught by the framework and goes to FlutterError.onError. A Future that fails with no listener goes to PlatformDispatcher.instance.onError.
class ErrorTestPage extends StatelessWidget {
const ErrorTestPage({super.key});
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () => throw Exception('Synchronous error in onPressed'),
child: const Text('Throw sync error'),
),
ElevatedButton(
onPressed: () async {
await Future<void>.delayed(const Duration(milliseconds: 100));
throw StateError('Asynchronous error after a delay');
},
child: const Text('Throw async error'),
),
],
);
}
}Replacing the red error screen
ErrorWidget.builder sets the widget shown in place of any widget whose build method threw. It replaces the default red error box.
void installErrorWidget() {
ErrorWidget.builder = (FlutterErrorDetails details) {
return const Material(
child: Center(child: Text('Something went wrong on this screen.')),
);
};
}Errors from other isolates
Errors in a spawned isolate do not reach your main-isolate handlers. Attach an error listener to receive them. The listener gets a two-item list: the error and its stack trace as a string.
import 'dart:isolate';
void listenToMainIsolateErrors() {
Isolate.current.addErrorListener(RawReceivePort((dynamic pair) {
final List<dynamic> errorAndStack = pair as List<dynamic>;
debugPrint('Isolate error: ${errorAndStack.first}');
debugPrint('Stack: ${errorAndStack.last}');
}).sendPort);
}runZonedGuarded and zone mismatches
runZonedGuarded is older code you will still see. It wraps main in an error zone. Current code should install the two global handlers instead. If you keep runZonedGuarded, call ensureInitialized() and runApp() in the same zone. Calling them in different zones triggers a zone mismatch warning.
Pitfalls
- Debug and release builds differ.
FlutterError.presentErrorprints only in debug mode, so verify reporting in a release or profile build. - A handler that throws or calls
setStatecan loop. Keep handlers simple and do not rethrow. - Errors from code outside Flutter, such as native callbacks, may bypass both handlers.
Exercise
Exercise
You add a FlutterError.onError handler and tap the sync-error button, but nothing is logged. What is the most likely cause?
Show answer
The handler was installed after runApp or never ran because main returned early, so the handler was not assigned before the error occurred. Assign both handlers in main() after WidgetsFlutterBinding.ensureInitialized() and before runApp().