Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 73 ยท Quality and performance

Error Handling, Logging and Crash Reporting

Catch every Flutter error: try/catch, FlutterError.onError, PlatformDispatcher.onError, custom error widgets, log levels, and Crashlytics or Sentry crash reports.

Every app fails somewhere: the network drops, a server returns something unexpected, a plugin throws on one phone model, a null slips through. The question is not whether errors happen but what the user sees, and whether you find out. A good app shows a calm message and a way forward, keeps running when it can, and quietly reports the problem so you can fix it.

This lesson covers the three places errors come from in Flutter, how to catch each one, how to replace the red error screen, how to log with levels, and how crash reporting services fit in.

Real vs stand-in. The Dart code is real Flutter code in read-only blocks: the site has no Flutter runtime and no crash-reporting backend. The live examples are JavaScript stand-ins for the three error channels, a leveled logger and a report-with-context pipeline.

Three places errors come from

Framework Build, layout and paint errors.
Async Uncaught errors in futures and streams.
Your calls Code inside try/catch you wrote.

Each one has its own catch point.

1 / 2

Errors you handle: try/catch

When you call something that can fail, handle the failure at the place where you know what to do about it. Dart separates Exception (expected, recoverable problems) from Error (programming bugs such as StateError or RangeError).

DART
Future<User> loadUser(String id) async {
  try {
    final response = await client.get(Uri.parse('$baseUrl/users/$id'))
        .timeout(const Duration(seconds: 10));
    if (response.statusCode == 404) {
      throw UserNotFound(id);
    }
    if (response.statusCode != 200) {
      throw ApiException(response.statusCode);
    }
    return User.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } on TimeoutException {
    throw const NetworkProblem('The server took too long to answer.');
  } on SocketException {
    throw const NetworkProblem('No internet connection.');
  } on FormatException catch (e, stack) {
    log.severe('Bad JSON from server', e, stack);
    throw const NetworkProblem('The server sent something unexpected.');
  }
}

Good habits:

  • Catch specific types with on. A bare catch (e) hides bugs.
  • Keep the stack trace: catch (e, stack). Rethrow with rethrow to preserve it; throw e loses it.
  • Turn low-level errors into domain errors your UI understands (NetworkProblem, UserNotFound), so widgets never parse HTTP codes (HTTP and JSON).
  • Use finally to clean up regardless of the outcome.
  • Never swallow silently with an empty catch {}.

In the UI, show failures as a state (loading, error with retry, data), as in FutureBuilder and StreamBuilder, rather than letting the exception escape.

Errors nobody caught

Whatever escapes your own handlers lands in one of two global hooks. Install both in main.

DART
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 1. Errors thrown by the Flutter framework: build, layout, paint, gestures.
  FlutterError.onError = (FlutterErrorDetails details) {
    FlutterError.presentError(details);          // still print in debug
    reporter.recordFlutterError(details);
  };

  // 2. Everything else: uncaught async errors, platform callbacks, isolates.
  PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
    reporter.recordError(error, stack);
    return true;                                  // handled: do not crash
  };

  runApp(const MyApp());
}
  • FlutterError.onError receives errors that the framework itself catches, for example an exception inside a widget's build or a failed paint. The app keeps running, with an error widget in place of the broken subtree (see below).
  • PlatformDispatcher.instance.onError receives errors that no one caught anywhere else, such as an exception in an unawaited Future or in a timer callback. Returning true says "I handled it"; returning false lets the default behavior continue.

Older code uses runZonedGuarded(() => runApp(...), onError). Zones still exist and are useful for scoping logging or timers, but with current Flutter versions PlatformDispatcher.onError is the recommended catch-all. One practical warning from the zones era: if you do use zones, call WidgetsFlutterBinding.ensureInitialized() and runApp in the same zone, otherwise you get a zone mismatch.

An error in one isolate does not reach these handlers automatically. For work in other isolates, listen to Isolate.current.addErrorListener or use Isolate.run, which forwards the error to the caller as a failed future.

JS Three error channels, one reporter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first widget error did not crash the whole frame: it became a placeholder and was reported. The unawaited rejection reached the global handler, while the third error was handled where it happened and translated for the user, with the original cause kept for the log.

Replacing the red screen

In debug builds a failed build shows a red error screen with details. In release builds it shows a plain gray box, which is confusing to users. Replace it with ErrorWidget.builder:

DART
void main() {
  ErrorWidget.builder = (FlutterErrorDetails details) {
    return const Material(
      child: Center(
        child: Padding(
          padding: EdgeInsets.all(24),
          child: Text(
            'Something went wrong on this screen. Please go back and try again.',
            textAlign: TextAlign.center,
          ),
        ),
      ),
    );
  };
  runApp(const MyApp());
}

Keep it simple: this widget runs when things are already broken, so it must not depend on anything fancy (providers, themes that might be missing). Show the real error text only in debug mode (kDebugMode).

Also design error states for each screen: an offline banner, a retry button, an empty list message. Those are normal parts of the UI, not exceptions.

Logging

print is fine while learning, but it has no levels, no filtering, and in release builds it can be slow and can leak data. Use a logger with levels:

Level Use for
fine / debug Details useful while developing
info Normal milestones: "user signed in"
warning Something odd that the app handled
severe / error Something failed

Dart ships dart:developer's log() and the official logging package; many apps use logger or talker. With logging:

DART
import 'package:logging/logging.dart';

final _log = Logger('CheckoutService');

void setupLogging() {
  Logger.root.level = kReleaseMode ? Level.WARNING : Level.ALL;
  Logger.root.onRecord.listen((record) {
    debugPrint('${record.level.name} ${record.loggerName}: ${record.message}');
    if (record.level >= Level.SEVERE) {
      reporter.recordError(record.error ?? record.message, record.stackTrace);
    }
  });
}

Future<void> pay() async {
  _log.info('Starting payment');
  try {
    await gateway.charge();
  } catch (e, s) {
    _log.severe('Payment failed', e, s);
  }
}

What to log: events and ids that help you understand a failure. What not to log: passwords, tokens, full card numbers, personal data. Logs end up in crash reports and files, so treat them as public (see security).

JS A leveled logger with a release filter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the release build the noisy messages disappear, the secret in the message is masked, and only severe records with an error object go to the reporting service.

Crash reporting services

Logs on a user's phone are useless to you. A crash reporting service collects errors from real devices, groups identical ones, and shows stack traces, device models, app versions and the steps before the crash. The two most common choices:

  • Firebase Crashlytics, part of Firebase. Free, simple, integrates with Android and iOS crash reporting.
  • Sentry, which works across many platforms (including Flutter web and desktop), supports performance tracing and can be self-hosted.

Wiring Crashlytics into the hooks you saw above looks like this:

DART
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;
  PlatformDispatcher.instance.onError = (error, stack) {
    FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
    return true;
  };

  runApp(const MyApp());
}

Sentry offers a wrapper, SentryFlutter.init((options) { options.dsn = '...'; }, appRunner: () => runApp(const MyApp())), which installs the same hooks for you.

Make reports useful:

  • Upload symbols/mapping files for release builds, especially if you obfuscate the code (--obfuscate --split-debug-info), otherwise stack traces are unreadable.
  • Add context: app version and build number, a user id (an opaque id, not an email), the current screen, and a few "breadcrumbs" like the last actions. Services have setCustomKey, log and breadcrumb APIs.
  • Report non-fatal errors too: a caught exception you want to track is recordError(e, s, fatal: false).
  • Respect privacy: ask for consent where the law requires it, never attach personal data, and consider disabling collection in debug builds.
JS Attaching context to a report

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Four events were recorded but only the latest three are kept, so a report always tells the story of the last few seconds without growing forever.

Putting it together

  1. Handle expected failures near the call, convert them to domain errors, and render error states.
  2. Install FlutterError.onError and PlatformDispatcher.instance.onError in main.
  3. Replace the release error widget with something calm.
  4. Log with levels, filter in release, never log secrets.
  5. Report to Crashlytics or Sentry with symbols and context.
  6. Watch the dashboard after every release, and fix the top crash first.

Errors are also a security topic: what you log and what you ship in the app can leak secrets. That is the next lesson: Security in Flutter Apps.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which hook receives errors thrown while building a widget?

    The framework catches build, layout and paint errors and reports them through FlutterError.onError.
  2. 2. What is the best way to catch an uncaught error from an unawaited Future?

    Errors that no one caught anywhere else reach PlatformDispatcher.instance.onError. Returning true marks them handled.
  3. 3. Why use catch (e, stack) and rethrow instead of throw e?

    rethrow preserves the original stack trace, which is what you need to debug the failure.
  4. 4. Which belongs in a log message?

    Log identifiers and events that explain a failure. Never log secrets or personal data.
  5. 5. You enabled --obfuscate for release builds. What do you need for readable crash reports?

    Obfuscated stack traces need the symbol files so the service can map names back to your code.

Summary

  • Handle expected failures with specific on clauses, keep stack traces, and convert errors into domain types the UI can show.
  • Install FlutterError.onError for framework errors and PlatformDispatcher.instance.onError for everything uncaught; zones are the older alternative.
  • Replace the release gray box with ErrorWidget.builder, and design error states into every screen.
  • Log with levels, filter in release builds and never record secrets.
  • Use Crashlytics or Sentry with symbol files, version info, breadcrumbs and non-fatal reports.

Next: Security in Flutter Apps