Sub topic 5
Handling async errors with `PlatformDispatcher.instance.onError`
Assume you know basic Dart syntax, async and await, Future, try/catch, and how a Flutter app starts with runApp(). This chapter focuses on errors that escape normal try/catch blocks and the Flutter framework.
What `PlatformDispatcher.onError` receives
Flutter has separate paths for different uncaught errors. Synchronous framework errors, such as failures during build, usually go to FlutterError.onError. An asynchronous error that nobody catches can reach PlatformDispatcher.instance.onError.
PlatformDispatcher connects the Flutter framework to the platform running the app. Its onError callback receives:
error: the thrown object.stack: the stack trace showing where the error occurred.
The callback must return a Boolean value. Returning true tells Flutter that your callback handled the error. Returning false tells Flutter that the error was not handled, so the platform may report it through its own mechanism.
Install the handler in `main()`
Install the handler before runApp(). Calling WidgetsFlutterBinding.ensureInitialized() first initializes the binding that connects Flutter services to the application.
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
debugPrint('Uncaught asynchronous error: $error');
debugPrint('Stack trace:\n$stack');
// Replace these lines with your reporting service.
return true;
};
runApp(const MaterialApp(
home: Scaffold(
body: Center(child: Text('Async error handler installed')),
),
));
}The handler is global for the root isolate, which is the main Dart execution context of the application. Keep it small. It should record the error and return. Do not perform complex recovery there, because recovery code can throw another error or hide the original failure.
Forward errors to a reporting service
A reporting service usually needs both the error and its stack trace. Keep reporting separate from handler installation so that you can replace debugPrint without changing the startup code.
class ErrorReporter {
static bool reportAsyncError(Object error, StackTrace stack) {
debugPrint('Sending error to the reporter: $error');
debugPrint('Stack trace:\n$stack');
// Example:
// crashService.recordError(error, stack, fatal: true);
return true;
}
}
void installAsyncErrorHandler() {
PlatformDispatcher.instance.onError = ErrorReporter.reportAsyncError;
}A real reporter may perform network work, but the callback should not depend on a successful network request before returning. Save the event locally or use the reporting SDK's non-blocking API when possible. Avoid logging sensitive values such as access tokens or passwords.
Trigger and verify an async error
This page deliberately creates an unhandled error after a delay. The Future is started without await or catchError, so the error has no local handler.
class ErrorTestPage extends StatelessWidget {
const ErrorTestPage({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: () {
Future<void>.delayed(const Duration(milliseconds: 100), () {
throw StateError('Test asynchronous failure');
});
},
child: const Text('Trigger async error'),
),
);
}
}Use this only in a controlled test screen. Check the console or your reporting dashboard and confirm that the error and stack trace arrive. Then remove the test trigger before releasing the app.
runZonedGuarded can still be useful for legacy code or code that depends on a particular Dart zone. It should not replace the platform handler as the primary Flutter-wide mechanism. A zone mismatch occurs when a callback is created in one zone but later invoked in another. Code that depends on zone-local values can then behave unexpectedly. Install global handlers during startup and use local try/catch around operations that have a known recovery path.
Exercise
What should PlatformDispatcher.instance.onError return after successfully recording an uncaught asynchronous error?
Show answer
It should return true, which tells Flutter that the error was handled.