Handling errors in Flutter
The Flutter framework catches errors that occur during callbackstriggered by the framework itself, including during build, layout, andpaint.
All these errors are routed to the FlutterError.onError handler. By default, this calls FlutterError.dumpErrorToConsole,which, as you might guess, dumps the error to the device logs. Whenrunning from an IDE, the inspector overrides this so that errors canalso be routed to the IDE’s console, allowing you to inspect theobjects mentioned in the message.
When an error occurs during the build phase, the ErrorWidget.buildercallback is invoked to build the widget that is used instead of theone that failed. By default, in debug mode this shows an error messagein red, and in release mode this shows a gray background.
You can override each of these, typically by setting them to values inyour void main()
function.
For example, to make your application quit immediately any time anerror is shown in release mode, you could use the following handler:
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.dumpErrorToConsole(details);
if (kReleaseMode)
exit(1);
};
runApp(MyApp());
}
// rest of `flutter create` code...
This handler can also be used to report errors to a logging service.For more details, see our cookbook chapter for reporting errors to a service.