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:

  1. import 'dart:io';
  2. import 'package:flutter/foundation.dart';
  3. import 'package:flutter/material.dart';
  4. void main() {
  5. FlutterError.onError = (FlutterErrorDetails details) {
  6. FlutterError.dumpErrorToConsole(details);
  7. if (kReleaseMode)
  8. exit(1);
  9. };
  10. runApp(MyApp());
  11. }
  12. // 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.