Sub topic 2
Reading FlutterErrorDetails and Keeping Console Output with presentError
This chapter assumes you know Dart's async/await and Futures, can build a simple Flutter app with runApp, and have read how framework errors differ from asynchronous errors.
Reading FlutterErrorDetails
FlutterError.onError receives a FlutterErrorDetails object for each framework error. Its main fields are:
exception: the error object.stack: the stack trace, which can be null.library: the name of the Flutter library that reported the error.context: a description of what Flutter was doing.
Call exceptionAsString() to get a readable message.
Keeping console output with presentError
Assigning FlutterError.onError replaces the default handler, which prints the error to the console. Call FlutterError.presentError(details) first to keep that output.
Handling async errors with PlatformDispatcher.instance.onError
Errors in Futures that nothing awaits or catches skip FlutterError.onError. They reach PlatformDispatcher.instance.onError, which takes the error and its stack trace.
Returning true or false from onError
The handler returns a bool. Returning true tells the engine the error is handled, so the app keeps running. Returning false tells the engine the error is still unhandled, so default platform handling applies.
Sending errors to a logging or crash-reporting service
Route both handlers to one reporter class. Replace the debugPrint calls with your service's API.
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details);
ErrorReporter.reportFlutterError(details);
};
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
ErrorReporter.reportAsyncError(error, stack);
return true;
};
runApp(const MyApp());
}
class ErrorReporter {
static void reportFlutterError(FlutterErrorDetails details) {
debugPrint('Framework error in ${details.library}: ${details.exceptionAsString()}');
debugPrint('${details.stack}');
}
static void reportAsyncError(Object error, StackTrace stack) {
debugPrint('Async 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('Hello'))));
}
}Exercise
In the code above, what happens to a framework error if you delete the FlutterError.presentError(details); line?
Show answer
The error still reaches the reporter, but it no longer prints to the console, because the custom handler replaced the default output.