Sub topic 9
Replacing the red error screen with ErrorWidget.builder
This chapter assumes you know basic Dart and Flutter widgets, and that you have already installed FlutterError.onError and PlatformDispatcher.instance.onError in main(). Those handlers decide where errors are reported. ErrorWidget.builder decides what the user sees when a widget fails to build. The two work together but do not replace each other.
What ErrorWidget.builder does
When a widget's build method throws, Flutter cannot draw that widget. The framework catches the exception and does two things, in this order:
- It reports the error through
FlutterError.reportError, which calls yourFlutterError.onErrorhandler. - It calls
ErrorWidget.builderwith theFlutterErrorDetailsand mounts the widget that the builder returns in place of the failed one.
ErrorWidget.builder is a static variable of type ErrorWidgetBuilder, which is Widget Function(FlutterErrorDetails details). Because it is static, one assignment affects every widget in the app. Only the failed subtree is replaced. The rest of the screen keeps working.
Default behavior
| Build mode | Default replacement |
|---|---|
| Debug | A red box with the exception message in yellow text |
| Profile and release | A plain gray box with no text |
In debug mode the red box helps you find the bug. In release mode the gray box is empty, so users see a blank rectangle and have no explanation. A custom builder is mostly useful for release builds.
Writing a replacement widget
Set the builder in main() after WidgetsFlutterBinding.ensureInitialized() and before runApp. The example below keeps the error handlers from earlier chapters, installs a custom builder, and includes a widget that always fails so you can see the result.
import 'dart:ui';
import 'package:flutter/material.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details);
debugPrint('Reported: ${details.exceptionAsString()}');
};
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
debugPrint('Uncaught async error: $error');
return true;
};
ErrorWidget.builder = (FlutterErrorDetails details) {
return FallbackView(
debugMessage: kDebugMode ? details.exceptionAsString() : null,
);
};
runApp(const MyApp());
}
class FallbackView extends StatelessWidget {
const FallbackView({super.key, this.debugMessage});
final String? debugMessage;
@override
Widget build(BuildContext context) {
const style = TextStyle(
color: Color(0xFF000000),
fontSize: 14,
decoration: TextDecoration.none,
);
return Directionality(
textDirection: TextDirection.ltr,
child: ColoredBox(
color: const Color(0xFFFFF3E0),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('Something went wrong on this screen.', style: style),
if (debugMessage != null) Text(debugMessage!, style: style),
],
),
),
),
);
}
}
class Bomb extends StatelessWidget {
const Bomb({super.key});
@override
Widget build(BuildContext context) {
throw StateError('Bomb failed to build');
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: HomePage());
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool _broken = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('ErrorWidget demo')),
body: Column(
children: [
ElevatedButton(
onPressed: () => setState(() => _broken = !_broken),
child: Text(_broken ? 'Repair' : 'Break'),
),
Expanded(
child: Center(
child: _broken ? const Bomb() : const Text('All good'),
),
),
],
),
);
}
}Tap Break. The Bomb widget throws, and FallbackView appears in its place while the app bar and button stay usable. The console shows the normal Flutter error output and the Reported: line, which confirms that FlutterError.onError still ran. Run the same code with flutter run --release and the debug message disappears, leaving only the friendly text.
Why the fallback widget is written defensively
The builder receives only FlutterErrorDetails. It has no BuildContext, and the widget it returns is mounted exactly where the failed widget was. That placement has several consequences.
- Missing ancestors. If the failure happened above
MaterialApp, there is noDirectionality,Theme, orMediaQuery. ATextwithoutDirectionalitythrows, and the fallback itself would fail. The example wraps its content inDirectionalityand uses explicit colors and a text style for that reason. - Unbounded constraints. The replacement gets the failed widget's constraints. Inside a
ListViewthe height is unbounded, so a widget that tries to fill the available height cannot work there.mainAxisSize: MainAxisSize.minkeeps the column compact. - Small slots. A failed icon in a toolbar may only have a 24-pixel box. A large message there will overflow. If your app has small slots, consider returning a small widget and accepting that it carries little information.
- One call per failure. If 100 list items fail, the builder runs 100 times. Keep it cheap.
The returned widget can use its own BuildContext in its build method, for example Theme.of(context). Do this only if you are sure a theme exists where failures occur. Otherwise the lookup falls back to defaults.
Keep reporting out of the builder
The builder is called during the build phase, and it can run many times for the same underlying bug, because each rebuild of the failing widget throws again. Report errors in FlutterError.onError, not in the builder.
If the same widget fails on every frame, FlutterError.onError also fires repeatedly. A reporting service usually needs deduplication, for example by comparing details.exception.runtimeType and the first lines of details.stack. Keep that logic in your reporter class.
Keeping the default in debug builds
The red screen with the message is useful during development. A common pattern is to save the original builder and delegate to it in debug mode.
void installErrorWidget() {
final ErrorWidgetBuilder previousBuilder = ErrorWidget.builder;
ErrorWidget.builder = (FlutterErrorDetails details) {
if (kDebugMode) {
return previousBuilder(details);
}
return const FallbackView();
};
}Capture previousBuilder before you assign the new builder. If you read ErrorWidget.builder inside the closure, it refers to your own builder and calls itself forever.
You can also run the custom view in debug mode, as the first example did, and show details.exceptionAsString() inside it. Choose whichever helps your team find bugs faster.
What the builder does not cover
ErrorWidget.builder applies only when a widget fails to build. It is not a general error screen.
| Error | Reaches `FlutterError.onError` | Reaches `ErrorWidget.builder` | Reaches `PlatformDispatcher.onError` |
|---|---|---|---|
| Exception in a widget's `build` | Yes | Yes | No |
| Exception thrown in a synchronous gesture callback such as `onPressed` | Yes | No | No |
| Exception during layout or paint | Yes | No | No |
| Failed `Future` with no listener | No | No | Yes |
A button that throws does not change the screen. The user sees nothing unless you show feedback yourself, for example with a SnackBar inside a try/catch. A global handler can log the failure but cannot know which screen to repair.
Testing the replacement
ErrorWidget.builder is global state. A test that changes it will affect every later test in the same process unless it restores the original. Set the builder inside the test and restore it with addTearDown.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class Bomb extends StatelessWidget {
const Bomb({super.key});
@override
Widget build(BuildContext context) {
throw StateError('Bomb failed to build');
}
}
void main() {
testWidgets('shows the fallback when build throws', (tester) async {
final ErrorWidgetBuilder original = ErrorWidget.builder;
addTearDown(() => ErrorWidget.builder = original);
ErrorWidget.builder = (FlutterErrorDetails details) {
return const Text('fallback', textDirection: TextDirection.ltr);
};
await tester.pumpWidget(const Bomb());
expect(find.text('fallback'), findsOneWidget);
expect(tester.takeException(), isA<StateError>());
});
}takeException() is required. The test framework treats a reported error as a failure unless the test retrieves it. The call also verifies that the original exception was reported and not swallowed.
Common mistakes
- Setting the builder after
runApp. Widgets built before the assignment use the old builder. Assign it inmain()beforerunApp. - Using
ScaffoldorMaterialAppinside the fallback. AScaffoldinside a small slot is oversized, and a nestedMaterialAppcan fail without a navigator or other dependencies. - Relying on the builder to catch everything. It does nothing for async errors, callbacks, or errors outside the widget tree.
- Hiding errors in release. A friendly fallback means users do not see failures, so your reporter becomes your only signal. Check that
FlutterError.onErrorforwards to a service before shipping. - Forgetting that the failure persists. The fallback replaces the widget, but it does not fix the cause. If the same data is bad on the next rebuild, the failure repeats.
Exercise
A screen shows a blank gray rectangle in a release build after a widget throws in build. You have installed FlutterError.onError but not ErrorWidget.builder. What happens in each case if you (a) add a custom ErrorWidget.builder that returns a message and (b) remove the FlutterError.onError handler?
Show answer
(a) The framework still reports the error to FlutterError.onError first, then the custom builder returns the message widget, so users see your text in place of the gray box and your reporting still runs. (b) Without the handler, FlutterError.onError falls back to its default, which prints the error to the console, so nothing is sent to your reporting service. The builder still shows the fallback widget, since it is independent of the handler.
Exercise
Why is final previous = ErrorWidget.builder; placed before the assignment in the debug-delegating pattern, and what happens if you read ErrorWidget.builder inside the new closure instead?
Show answer
The closure runs later, after ErrorWidget.builder has been replaced by the closure itself. Reading ErrorWidget.builder inside it calls the custom builder again, which calls itself without end and overflows the stack. Capturing the original value in a local variable first keeps a reference to the default builder.