Sub topic 1
Two Kinds of Uncaught Errors: Framework Errors and Async Errors
Prerequisites
This chapter assumes you know Dart async/await and Futures, can build a simple Flutter app with runApp, and understand try/catch.
Two Channels for Uncaught Errors
Flutter sends errors that nothing in your code catches through one of two channels:
- Framework errors happen during build, layout, paint, and synchronous gesture callbacks. Flutter catches them and passes them to
FlutterError.onError. - Async errors happen inside a
Futureor async callback that has no listener. They reachPlatformDispatcher.instance.onError.
| Error source | Handler |
|---|---|
| Build, layout, paint, synchronous gesture callbacks | `FlutterError.onError` |
| Unhandled `Future` or async callback | `PlatformDispatcher.instance.onError` |
Calling WidgetsFlutterBinding.ensureInitialized First
Install both handlers in main(), before runApp. Set the handlers only after WidgetsFlutterBinding.ensureInitialized() returns. That call connects Flutter's bindings to the engine. Skipping it can leave the handlers unready, so call it first.
Handling Framework Errors with FlutterError.onError
FlutterError.onError receives a FlutterErrorDetails object. It holds the exception, the stack trace, and the name of the library that raised the error. Assigning a handler replaces Flutter's default behavior, so call FlutterError.presentError(details) to keep the red error output in the console.
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()}');
};
runApp(
const MaterialApp(
home: Scaffold(body: Center(child: Text('Hello'))),
),
);
}:::callout note FlutterError.onError handles only errors from the framework. An unhandled Future error bypasses it and goes to PlatformDispatcher.instance.onError. :::
Exercise
Exercise
A button's onPressed callback throws Exception('boom') synchronously. Which handler receives it, and why?
Show answer
FlutterError.onError. The framework calls onPressed during gesture handling and catches the synchronous exception, then passes it to FlutterError.onError.