Sub topic 1
Two kinds of uncaught errors: framework errors and async errors
A Flutter app has two separate places where an uncaught error can end up. If you only watch one of them, you will miss real crashes. This chapter explains which error goes where, why the split exists, and how to see it happen in a small app.
Prerequisites
This chapter assumes you already know:
- Basic Dart syntax, including
async/awaitandFuture. - How to build a simple Flutter app with widgets and
runApp. - How
try/catchworks in Dart, and what an unhandled exception is.
You do not need any crash-reporting service. All examples print to the console.
What "uncaught" means
An error is uncaught when it is thrown and no try/catch or catchError anywhere on the call path handles it. Dart then has to decide what to do with it. In a plain Dart program, an uncaught error in the main isolate usually stops the program. A Flutter app keeps running, because the framework and the engine intercept the error and route it somewhere.
Where it is routed depends on who caught it:
- The Flutter framework catches some errors itself, because it is the code calling your code. It wraps its calls to
build, layout, paint and gesture callbacks intry/catch. When something throws, the framework wraps the error in aFlutterErrorDetailsobject and hands it toFlutterError.onError. - Everything else escapes the framework. The typical case is a
Futurethat completes with an error while nothing is listening. Dart's zone machinery reports it as an uncaught asynchronous error, and Flutter forwards it toPlatformDispatcher.instance.onError.
These are two different hooks with different signatures and different rules.
Channel 1: framework errors
FlutterError.onError is a static field of type void Function(FlutterErrorDetails). The framework calls it whenever it catches an exception in code it is running synchronously. The most common sources are:
- Build. An exception thrown inside a widget's
buildmethod, for example a null check failing or a bad index into a list. - Layout. Constraint violations and render object failures. A
RenderFlexoverflow is reported this way. - Paint. Exceptions in
CustomPainter.paintor in a render object'spaint. - Gesture callbacks. A synchronous exception thrown directly in
onPressed,onTapand similar callbacks. The gesture system calls your callback inside atry/catchand reports the failure. - Other framework-managed callbacks. Animation tickers, some scheduler callbacks, and image loading failures also report through this channel.
By default, FlutterError.onError points at FlutterError.presentError. That is why you see the long, formatted error block in the debug console. Replacing the field removes that output unless you call presentError yourself. Later chapters cover that detail. For now, remember that this channel is for errors the framework caught on its own.
A build error also has a visible effect on screen. The framework replaces the broken widget with an ErrorWidget, which is the red screen in debug mode and a gray box in release mode. The error is also reported through FlutterError.onError.
Channel 2: uncaught asynchronous errors
PlatformDispatcher.instance.onError is a field of type bool Function(Object error, StackTrace stack). It receives errors that no one caught, and that the framework never saw. These errors usually come from code that runs later, outside any framework try/catch:
- A
Futurethat fails when noawait,.catchErrorortry/catchis attached to it. - An exception thrown after an
awaitin anasyncfunction whose returnedFuturenobody observes. - An exception thrown in a
Timercallback. - An exception thrown in a
Streamlistener that has noonError. - An exception in a microtask.
The key point is that an async callback hides its errors from the framework. Look at this:
onPressed: () async {
await Future<void>.delayed(const Duration(milliseconds: 100));
throw StateError('Asynchronous error after a delay');
},The gesture system calls this closure inside its try/catch. The call returns right away with a Future. No exception has been thrown yet, so the try/catch sees nothing. When the exception happens 100 ms later, it turns the returned Future into a failed one. The framework ignores that Future, so nobody listens, and the error is reported as uncaught asynchronous. It reaches PlatformDispatcher.instance.onError, not FlutterError.onError.
The same closure written without async would throw immediately, inside the framework's try/catch, and the error would go to FlutterError.onError. This is the most common source of confusion about the two channels. The difference comes down to when the exception is thrown relative to the framework's call.
The return value
The onError function on PlatformDispatcher returns a bool. Returning true tells the engine that you handled the error, so it does nothing more. Returning false lets the engine apply its default behavior, which is to print the error in the console. The next chapters cover this in depth. The examples in this chapter always return true.
Side-by-side comparison
| Row | `FlutterError.onError` | `PlatformDispatcher.instance.onError` |
|---|---|---|
| Who catches the error | The Flutter framework, in its own `try`/`catch` | Dart's uncaught-error mechanism, forwarded by the engine |
| Signature | `void Function(FlutterErrorDetails)` | `bool Function(Object, StackTrace)` |
| Typical sources | `build`, layout, paint, synchronous gesture callbacks | Failed `Future`s, `Timer` callbacks, stream listeners |
| Information provided | `FlutterErrorDetails`: exception, stack, library, context | Only the error and its stack trace |
| Default behavior | `FlutterError.presentError` prints to the console | Printed to the console if you return `false` |
| Return value | None | `true` means handled |
The two hooks work independently. Installing one does not affect the other. A thrown error reaches exactly one of them, never both.
A decision diagram
Read the diagram from the top. The first question is always whether your own code handles the error. If it does, neither hook runs. The second question is whether the framework was on the call stack when the exception was thrown.
Installing both handlers
Both hooks are plain assignments, so you set them once at startup, before runApp. The example below is a complete app you can run. It also adds two buttons so you can watch each channel fire.
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
// Channel 1: errors caught by the Flutter framework.
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details); // keep the default console output
debugPrint('[framework channel] ${details.exceptionAsString()}');
};
// Channel 2: uncaught errors that the framework does not catch.
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
debugPrint('[async channel] $error');
return true; // true means the error was handled
};
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: Scaffold(body: ErrorTestPage()));
}
}
class ErrorTestPage extends StatelessWidget {
const ErrorTestPage({super.key});
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
// Thrown synchronously inside the gesture system's try/catch.
onPressed: () => throw Exception('Synchronous error in onPressed'),
child: const Text('Throw sync error'),
),
ElevatedButton(
// The returned Future fails with nobody listening.
onPressed: () async {
await Future<void>.delayed(const Duration(milliseconds: 100));
throw StateError('Asynchronous error after a delay');
},
child: const Text('Throw async error'),
),
],
);
}
}Why `ensureInitialized` comes first
WidgetsFlutterBinding.ensureInitialized() creates the binding that connects the framework to the engine. It must run before any code that talks to the engine or to platform plugins. It is also the safest first line when you assign handlers, because it guarantees the framework is set up before any error can occur. If main is async and you await plugin setup before runApp, call ensureInitialized before the first await.
What you should see
Run the app in debug mode and press each button. You should see:
- Throw sync error. The console prints the standard framework error block from
presentError, followed by your[framework channel]line. Your async line does not appear. - Throw async error. About 100 ms after the tap, the console prints only the
[async channel]line. No framework error block appears, because you did not callpresentErrorin this handler and returnedtrue.
If both lines appear for a single press, the error was caught twice, which means your own code is rethrowing it somewhere. Check for a catch block that rethrows.
What neither handler sees
Knowing the gaps saves debugging time. Later chapters return to each of these.
- Errors you handle. If your own
try/catchswallows an exception, no hook runs. This is correct behavior, but it also means that acatch (_) {}hides problems from your reporting. - Errors in other isolates. An exception in a background isolate does not reach
PlatformDispatcher.instance.onErroron the main isolate. That isolate needs its own error listener. - Errors before the handlers are installed. Any exception thrown in
mainbefore the assignments run is not routed to your code. Install the handlers as early as possible. - Native crashes. A crash in platform code (Kotlin, Swift, C++) is not a Dart exception, so neither hook sees it. A native crash reporter covers that.
Common mistakes at this stage
- Installing only
FlutterError.onError. This catches build errors and sync callback errors, but failed network calls and timer errors slip through. The app seems to work, and the failures only show up in the console. - Assuming
asynccallbacks report like sync ones. As shown above, anasynconPressedsends its errors to the second channel. Reports that group errors by channel should expect that. - Dropping
presentErrorand losing console output. ReplacingFlutterError.onErrorwithout callingFlutterError.presentErrormakes framework errors silent during development. - Reading
FlutterErrorDetailsfields from the async channel. That handler receives only anObjectand aStackTrace. There is nolibraryorcontext.
Summary
- Flutter has two uncaught-error channels:
FlutterError.onErrorfor errors the framework catches, andPlatformDispatcher.instance.onErrorfor uncaught asynchronous errors. - The deciding factor is whether the framework's own
try/catchwas on the call stack when the exception was thrown. - An
asynccallback moves its failures to the second channel, because the framework only sees the returnedFuture. - Install both handlers in
main()afterWidgetsFlutterBinding.ensureInitialized()and beforerunApp. - Some errors reach neither handler: errors you catch yourself, errors in other isolates, errors before installation, and native crashes.
Exercise
In an ElevatedButton, you write onPressed: () async { throw Exception('boom'); }. There is no await before the throw. Which handler receives the error, and why?
Show answer
PlatformDispatcher.instance.onError. An async function never throws synchronously. It catches the exception and completes its returned Future with an error. The framework calls the closure, gets back a Future it does not observe, and sees no exception. The failed Future has no listener, so the error becomes an uncaught asynchronous error. The missing await does not change this.
Exercise
A widget's build method contains final first = items[0]; and items is empty. Which handler is called, what does the user see on screen, and what object do you receive?
Show answer
FlutterError.onError is called. The framework runs build inside its own try/catch, so it catches the RangeError. It replaces the broken widget with an ErrorWidget (a red screen in debug mode, a gray box in release mode). Your handler receives a FlutterErrorDetails object with the exception, the stack trace, and context such as the library name.