Sub topic 4
Reading FlutterErrorDetails and keeping console output with presentError
This chapter assumes you can write basic Dart and have already installed FlutterError.onError in main() after WidgetsFlutterBinding.ensureInitialized(). Earlier chapters showed that the framework hands every error it catches to that handler. Here you look at the object it passes in, FlutterErrorDetails, and at the call that keeps Flutter's normal console output working once you replace the default handler.
What FlutterErrorDetails contains
FlutterErrorDetails is an immutable record the framework builds when it catches an error. It bundles the exception with information about where and why it was caught. A handler that reads only exception throws most of that away.
| Field or method | Type | What it tells you |
|---|---|---|
| `exception` | `Object` | The thrown object. It is often an `Exception` or `Error`, but Dart lets code throw any object. |
| `stack` | `StackTrace?` | The stack trace at the throw site. It can be `null`. |
| `library` | `String?` | A short name for the part of the framework that caught the error, such as a rendering or gesture library. |
| `context` | `DiagnosticsNode?` | A sentence describing what the framework was doing, such as "while handling a gesture". |
| `informationCollector` | `InformationCollector?` | A callback that produces extra diagnostic lines, for example the widget ancestry. |
| `silent` | `bool` | `true` when the framework considers the error not worth showing to the user by default. |
| `summary` | `DiagnosticsNode` | A one-line description of the problem. |
| `exceptionAsString()` | `String` | The exception rendered as text. |
The library and context fields are what make framework errors easier to triage than plain exceptions. Two errors that both say FormatException can have different contexts: one thrown while building a widget, the other while handling a tap. Grouping reports by library and context in your reporting service often separates real bugs from noise.
Reading the fields in a handler
The example below is a complete app. A helper prints each field, and a button throws a FormatException from onPressed. The framework catches exceptions thrown from gesture callbacks, so this one reaches FlutterError.onError.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void describeError(FlutterErrorDetails details) {
debugPrint('--- error report ---');
debugPrint('summary: ${details.summary}');
debugPrint('exception: ${details.exceptionAsString()}');
debugPrint('type: ${details.exception.runtimeType}');
debugPrint('library: ${details.library ?? 'unknown'}');
debugPrint('context: ${details.context?.toDescription() ?? 'none'}');
debugPrint('silent: ${details.silent}');
debugPrint('stack: ${details.stack ?? 'no stack trace'}');
}
void main() {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details);
describeError(details);
};
runApp(const DemoApp());
}
class DemoApp extends StatelessWidget {
const DemoApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () => throw const FormatException('Bad input'),
child: const Text('Throw'),
),
),
),
);
}
}Run it in debug mode and tap the button. The console shows two things. First comes Flutter's own formatted error block, produced by presentError. Then comes the shorter report from describeError. The context line should read something like "while handling a gesture", which tells you which part of the framework was running.
Details worth knowing
exceptionAsString()is safer thanexception.toString()for display. It formats some framework exceptions in a friendlier way and is what the default output uses.details.exceptionis typedObject, notException. Throwing aStringor anintis legal Dart, so never cast it without checking.contextis aDiagnosticsNode, a structured description object. CalltoDescription()to get plain text.informationCollectoris a function, not data. Calling it can be expensive, because it may walk the widget tree. Most reporting code skips it and relies onstackandcontext.
Keeping console output with presentError
FlutterError.presentError is the function that prints the familiar multi-line error block. By default, FlutterError.onError is set to call it. When you assign your own function to FlutterError.onError, you replace that default. If your function does not call presentError, nothing is printed and the console goes quiet during development.
FlutterError.onError = (FlutterErrorDetails details) {
// Nothing printed here: the error appears to vanish in the console.
sendToService(details);
};This is the most common mistake with the handler, and it hides real bugs. You see a blank screen or a failed tap, and the console says nothing. Calling presentError first restores the output:
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details);
sendToService(details);
};The default output is more than a one-line message. In debug mode it prints the exception, the context, the relevant widget ancestry, and a filtered stack trace with the framework's internal frames removed. To avoid flooding the console, repeated errors in a short span are printed in a shorter form after the first. If you build your own printing with debugPrint, you get none of this filtering.
How the pieces fit together
Your handler sits in the middle and decides what happens next. The framework does not call presentError for you once you replace the handler.
Chaining with the previous handler
Another package may have already set FlutterError.onError. Crash-reporting SDKs often do this during their own setup. If you overwrite the value, their hook stops running. A safer pattern is to save the current handler and call it from yours:
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
void installChainedHandler() {
final FlutterExceptionHandler? previous = FlutterError.onError;
FlutterError.onError = (FlutterErrorDetails details) {
// The default value of onError is presentError, so this usually
// keeps the console output. Another SDK's hook runs here too.
previous?.call(details);
debugPrint('Reported: ${details.exceptionAsString()}');
};
}Two cautions apply:
- Call
installChainedHandler()once. Each extra call wraps the previous wrapper, so every error is reported twice, then three times, and so on. - If the previous handler is
null, nothing is printed. CallingFlutterError.presentError(details)explicitly is more predictable when you control the whole setup. Chain only when another component may own the hook.
Routing your own caught errors through the same path
FlutterError.reportError lets code you catch yourself flow through FlutterError.onError. This is useful when you want one reporting path for errors you handle gracefully and still want recorded.
import 'package:flutter/foundation.dart';
int? parseQuantity(String text) {
try {
return int.parse(text);
} catch (error, stack) {
FlutterError.reportError(
FlutterErrorDetails(
exception: error,
stack: stack,
library: 'checkout form',
context: ErrorDescription('while parsing the quantity field'),
),
);
return null;
}
}You choose library and context, so these values become the labels you filter on later. ErrorDescription is a diagnostics class from package:flutter/foundation.dart that turns a plain sentence into a DiagnosticsNode. Write the context so it completes the phrase "The error was caught ...", for example "while parsing the quantity field".
Edge cases
The stack can be null
stack is nullable. Some errors are created without a trace, and a throw of a non-Error object still has a trace at the throw site, but code that builds FlutterErrorDetails by hand may omit it. A reporting call that does details.stack! can itself crash. Use a fallback instead:
final StackTrace stack = details.stack ?? StackTrace.current;StackTrace.current points at your handler, not at the original problem, so mark such reports as having no original trace if your service allows it.
Silent errors
When silent is true, the framework signals that an error need not be shown to the user by default. Decide deliberately whether your reporting service should ignore these. Dropping them hides problems. Sending all of them can add noise. A common approach is to send them but tag them, so you can filter later.
Errors inside the handler
Your handler runs inside the framework's error path. If it throws, the new error is not guaranteed to reach any handler, and it can obscure the original one. Keep handlers short. Wrap any reporting call in its own try/catch, and never call code from the handler that can trigger a rebuild, because a rebuild that throws again calls the handler again. The pitfalls chapter returns to infinite loops in detail.
One handler, one error type
FlutterError.onError receives errors the framework catches. Uncaught asynchronous errors, such as a failed Future that nothing awaits, arrive through PlatformDispatcher.instance.onError instead, and that callback receives a raw Object and StackTrace, not a FlutterErrorDetails. If you want a single reporting format, convert at the boundary:
import 'dart:ui';
import 'package:flutter/foundation.dart';
void installBothHandlers() {
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details);
debugPrint('framework: ${details.exceptionAsString()}');
};
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
FlutterError.presentError(
FlutterErrorDetails(
exception: error,
stack: stack,
library: 'async',
context: ErrorDescription('while running an asynchronous task'),
),
);
return true;
};
}Here the async handler wraps the raw error in a FlutterErrorDetails only to reuse presentError for consistent console output. It does not call FlutterError.reportError, because that would route the error back through FlutterError.onError and into your framework reporting path. Whether you want that depends on whether you treat both kinds of error alike.
Summary of rules
- Read
libraryandcontextto learn where the framework caught the error, not only what was thrown. - Treat
stackas nullable andexceptionas any object. - Call
FlutterError.presentError(details)in your handler to keep the console output. - Save and call the previous handler only when another component may have installed one, and install your chain once.
- Use
FlutterError.reportErrorto send errors you catch yourself through the same path. - Keep the handler small and guarded, so it cannot become a source of errors.
Exercise
You assign FlutterError.onError = (details) { uploadToServer(details); } and later notice that when a widget fails to build during development, nothing appears in the console. Why does this happen, and what one-line change restores the output?
Show answer
The default value of FlutterError.onError calls FlutterError.presentError, which prints the formatted error block. Assigning your own function replaces that default, and your function never calls presentError, so nothing is printed. Adding FlutterError.presentError(details); as the first line of the handler restores the console output.
Exercise
A teammate writes details.stack!.toString() in the handler and the app sometimes throws inside the handler. What is wrong, and how would you write it safely?
Show answer
The stack field of FlutterErrorDetails is a nullable StackTrace?, so the null assertion operator fails when it is null. Use a fallback such as details.stack ?? StackTrace.current, or check for null and send the report without a trace.
Exercise
You call installChainedHandler() from main() and also from a plugin initialization function. Each error is now reported twice. What happened, and how do you fix it?
Show answer
Each call saves the current FlutterError.onError as previous and wraps it in a new handler. The second call wraps the first wrapper, so both reporting lines run for every error. Install the chain from exactly one place, for example by calling it once in main().