Sub topic 3
Handling Framework Errors with `FlutterError.onError`
Assume you know basic Dart syntax, async and await, Future, try/catch, widgets, and runApp. This chapter focuses on errors that the Flutter framework catches while it is processing your widget tree or callbacks.
What `FlutterError.onError` receives
Flutter catches many synchronous errors before they escape to the platform. Examples include errors during:
- A widget's
buildmethod - Layout and painting
- Gesture callbacks such as
onPressed - Other framework-managed callbacks
Flutter sends details about these errors to the FlutterError.onError callback. The callback receives a FlutterErrorDetails object. That object contains the exception, stack trace, library name, context, and other debugging information.
Flutter installs a default handler. In debug mode, the default handler usually prints a detailed error and shows a red error display. Installing your own handler replaces that default behavior, so call FlutterError.presentError if you still want Flutter's normal console output.
Install the handler in `main`
Install the handler before calling runApp. Calling WidgetsFlutterBinding.ensureInitialized first initializes the binding that connects your Dart code to Flutter's engine and platform services.
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()}',
);
debugPrint('Library: ${details.library}');
debugPrint('Stack: ${details.stack}');
};
runApp(const ErrorDemoApp());
}
class ErrorDemoApp extends StatelessWidget {
const ErrorDemoApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Error demo')),
body: const Center(child: ErrorTestButton()),
),
);
}
}
class ErrorTestButton extends StatelessWidget {
const ErrorTestButton({super.key});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
throw StateError('The test button failed');
},
child: const Text('Throw framework error'),
);
}
}When you press the button, the callback throws synchronously. Because Flutter invokes the callback, the framework catches the exception and calls FlutterError.onError.
The handler should record the error and return. Do not use it to repair application state or display a new page. Error handling code that throws another exception can hide the original failure.
Read and report the error details
A crash-reporting service usually needs at least:
details.exception, the thrown objectdetails.stack, the stack tracedetails.library, the Flutter library that reported the failuredetails.context, when available
Keep reporting in a separate class so changing services does not change how the handler is installed.
class ErrorReporter {
static void reportFlutterError(FlutterErrorDetails details) {
debugPrint('Exception: ${details.exception}');
debugPrint('Stack: ${details.stack}');
debugPrint('Library: ${details.library}');
// Send the exception and stack to your approved reporting service here.
}
}
void installFlutterErrorHandler() {
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details);
ErrorReporter.reportFlutterError(details);
};
}In production, avoid sending secrets, passwords, tokens, or private user data. Also decide whether the same error should be reported once or many times. Repeated build failures can generate a large number of duplicate reports.
>callout note > FlutterError.onError is for errors reported through Flutter's framework. It is not a universal replacement for try/catch, and it does not replace the separate handler for uncaught asynchronous errors.
Test the handler deliberately
A handler is useful only if you know it runs in the environments where you depend on it. Add a temporary test action, press it, and confirm that the console and reporting service receive the exception and stack trace. Remove or disable the action before releasing the application.
Remember that a caught error never reaches the global handler:
try {
throw StateError('Handled locally');
} catch (error, stack) {
debugPrint('Handled here: $error');
debugPrint('$stack');
}This is expected. Global handlers report errors that remain uncaught by the local code and framework path.
Exercise
Exercise
Why should a custom FlutterError.onError handler call FlutterError.presentError?
Show answer
Assigning a custom handler replaces Flutter's default handler. Calling presentError preserves Flutter's normal console reporting while your code records or forwards the error.