On this page13 sections
Lecture 014: Catching Errors & Testing a Crash
| Category | 4: Crashlytics |
| Lecture | 014 of 014 |
| Estimated video length | 16 min |
| Target | Flutter 3.44 · Dart 3.12 · FlutterFire (latest) |
| Level | Intermediate |
Crashlytics is installed, but Flutter catches its own errors and only prints them. We hand every kind of error to Crashlytics, then crash the app on purpose to prove it works.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Practice Questions · Answers · Takeaways · Full Code
Prerequisites
Lecture 013: Crashlytics added and enabled.
Learning Objectives
- Send Flutter framework errors with
FlutterError.onError - Send uncaught async errors with
PlatformDispatcher.instance.onError - Know when
runZonedGuardedis still useful - Record caught errors and add context
- Test with a real crash
1. Two Kinds of Errors
| Kind | Example | Hook |
|---|---|---|
| Framework errors: thrown while Flutter builds, lays out or paints | a null in build, overflow | FlutterError.onError |
Async errors: thrown in a Future or callback nobody catches | a failed await in a button handler | PlatformDispatcher.instance.onError |
2. Hooking Both
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;
PlatformDispatcher.instance.onError = (error, stack) {
FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
return true; // "handled" - don't also print it as unhandled
};Put both in main, after Firebase.initializeApp and before runApp. PlatformDispatcher
comes from dart:ui (Flutter's material.dart exports it).
3. runZonedGuarded
Older guides wrap runApp in runZonedGuarded to catch async errors:
runZonedGuarded(
() => runApp(const MyApp()),
(error, stack) => FirebaseCrashlytics.instance.recordError(error, stack, fatal: true),
);PlatformDispatcher.instance.onError now does the same job, so you don't need both. If you do
use a zone, everything, including WidgetsFlutterBinding.ensureInitialized(), must run inside
it, or Flutter warns about a "Zone mismatch".
4. Errors You Catch Yourself
Not every error should crash the app: but you still want to know about it:
try {
await paymentService.charge(amount);
} catch (e, stack) {
FirebaseCrashlytics.instance.recordError(e, stack, reason: 'charge failed');
showError('Payment failed, please try again.');
}These show up as non-fatal issues. Add context to every report:
FirebaseCrashlytics.instance.setUserIdentifier('user_123');
FirebaseCrashlytics.instance.setCustomKey('plan', 'pro');
FirebaseCrashlytics.instance.log('Opened checkout'); // breadcrumb before a crashCode Examples
Example 1: The Complete main.dart
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(!kDebugMode);
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;
PlatformDispatcher.instance.onError = (error, stack) {
FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
return true;
};
runApp(const MyApp());
}Example 2: Crash on Purpose
Add two test buttons to a screen:
// An uncaught async error → PlatformDispatcher.onError
FilledButton(
onPressed: () {
Future<void>.delayed(const Duration(milliseconds: 200), () {
throw StateError('Real uncaught async crash');
});
},
child: const Text('Throw async error'),
),
// A native crash → the app closes immediately
OutlinedButton(
onPressed: () => FirebaseCrashlytics.instance.crash(),
child: const Text('Force native crash'),
),To test:
- Temporarily use
setCrashlyticsCollectionEnabled(true). - Run the app without the debugger:
flutter run --release(the debugger catches crashes before Crashlytics can). - Tap a button. For
crash(), the app closes. - Open the app again: reports are sent on the next launch.
- Within a few minutes, Crashlytics in the console shows the issue with its stack trace.
Remove the test buttons and restore !kDebugMode afterwards.
Common Beginner Mistakes
1. Testing with the debugger attached: the IDE pauses on the error; nothing is sent.
2. Not reopening the app: native crash reports upload on the next launch.
3. Using both runZonedGuarded and PlatformDispatcher with ensureInitialized outside the
zone: a "Zone mismatch" warning. Pick PlatformDispatcher.
4. Leaving crash() buttons in the release: users will find them.
Best Practices
- Hook
FlutterError.onErrorandPlatformDispatcher.instance.onErrorin every app. - Record caught errors as non-fatal with a
reason. - Add a user identifier and breadcrumbs so reports are easy to reproduce.
- Check the Crashlytics dashboard after each release.
Practice Questions
- Which hook catches an error thrown inside
build? - Which hook catches an exception from an un-awaited
Future? - Why run the test with
flutter run --release? - How do you report an error you caught without crashing?
Practice Answers
FlutterError.onError.PlatformDispatcher.instance.onError.- The debugger catches the error first, so Crashlytics never sees it.
FirebaseCrashlytics.instance.recordError(e, stack, reason: '...').
Key Takeaways
- Framework errors →
FlutterError.onError; async errors →PlatformDispatcher.instance.onError. runZonedGuardedis optional now; if used, put everything inside the zone.recordErrorreports caught errors as non-fatal; add keys and logs for context.- Test without the debugger, then reopen the app to send the report.
Full Code (Copy-Paste Reference)
The complete, finished app: every file, as it stands at the end of the course. The two test-crash buttons are shown but commented out: the lecture's own advice is to remove them (or guard them behind a debug flag) before release.
lib/notification_status.dart
class NotificationStatus {
static const promoAdded = 'PROMO_ADDED_NOTIFICATION';
static const general = 'GENERAL_NOTIFICATION';
}lib/dialog_promo_code.dart
import 'package:flutter/material.dart';
import 'analytics_service.dart';
class DialogPromoCode extends StatelessWidget {
const DialogPromoCode({
super.key,
required this.title,
required this.body,
required this.type,
required this.imageUrl,
this.promoCode = '',
this.discountPercent = 0,
});
final String title;
final String body;
final String type;
final String imageUrl;
final String promoCode;
final int discountPercent;
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(title),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (imageUrl.isNotEmpty)
ClipRRect(
borderRadius: BorderRadius.circular(12),
child: Image.network(imageUrl, height: 140, fit: BoxFit.cover),
),
const SizedBox(height: 12),
Text(body),
],
),
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK')),
if (promoCode.isNotEmpty)
FilledButton(
onPressed: () {
AnalyticsService.promoOpened(promoCode, discountPercent);
Navigator.pop(context);
},
child: const Text('Use code'),
),
],
);
}
}lib/analytics_service.dart
import 'package:firebase_analytics/firebase_analytics.dart';
class AnalyticsService {
static final FirebaseAnalytics _analytics = FirebaseAnalytics.instance;
static Future<void> promoOpened(String code, int percent) {
return _analytics.logEvent(
name: 'promo_opened',
parameters: {'promo_code': code, 'discount_percent': percent},
);
}
static Future<void> buttonTapped(String button) {
return _analytics.logEvent(
name: 'button_tapped',
parameters: {'button': button},
);
}
static Future<void> loggedIn(String method) {
return _analytics.logLogin(loginMethod: method);
}
}lib/firebase_notification_handling.dart
import 'dart:async';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dialog_promo_code.dart';
import 'notification_status.dart';
class FirebaseNotificationHandling {
static Future<void> registerNotificationPermission() async {
final settings = await FirebaseMessaging.instance.requestPermission(
alert: true,
badge: true,
sound: true,
);
print('Notification permission: ${settings.authorizationStatus}');
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}
static void firebaseOnMessageNotificationHandle(
GlobalKey<NavigatorState> navigatorKey) {
FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) {
if (message != null) {
notificationHandler(navigatorKey, 2, message);
}
});
FirebaseMessaging.onMessageOpenedApp.listen((message) {
notificationHandler(navigatorKey, 2, message);
});
FirebaseMessaging.onMessage.listen((message) {
notificationHandler(navigatorKey, 1, message);
});
}
static Future<void> notificationHandler(GlobalKey<NavigatorState> navigatorKey,
int delaySeconds, RemoteMessage message) async {
final data = message.data;
final type = data['noti_type'] as String? ?? '';
if (type != NotificationStatus.promoAdded && type != NotificationStatus.general) {
return;
}
final title = data['noti_title'] as String? ?? '';
final body = data['noti_body'] as String? ?? '';
final imageUrl = data['image_url'] as String? ?? '';
await Future.delayed(Duration(seconds: delaySeconds));
final context = navigatorKey.currentContext;
if (context == null || !context.mounted) return;
showDialog(
context: context,
barrierDismissible: true,
builder: (_) => DialogPromoCode(title: title, body: body, type: type, imageUrl: imageUrl),
);
}
static StreamSubscription<String>? _registeredSub;
static Future<void> registerWithFcm() async {
_registeredSub ??= FirebaseMessaging.instance.onRegistered.listen((fid) {
debugPrint('FCM_REGISTERED $fid');
});
try {
await FirebaseMessaging.instance.register();
} catch (e) {
debugPrint('FCM_REGISTER_ERROR $e');
}
}
}lib/main.dart
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'firebase_notification_handling.dart';
import 'firebase_options.dart';
@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
print('Background message: ${message.data}');
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(!kDebugMode);
// Framework errors (thrown while Flutter builds/lays out/paints).
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;
// Uncaught async errors (a Future or callback nobody awaited/caught).
PlatformDispatcher.instance.onError = (error, stack) {
FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
return true; // "handled" - stop it from also printing as unhandled
};
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
static final navigatorKey = GlobalKey<NavigatorState>();
static final FirebaseAnalytics analytics = FirebaseAnalytics.instance;
static final FirebaseAnalyticsObserver observer =
FirebaseAnalyticsObserver(analytics: analytics);
@override
void initState() {
super.initState();
FirebaseNotificationHandling.registerNotificationPermission();
FirebaseNotificationHandling.firebaseOnMessageNotificationHandle(navigatorKey);
FirebaseNotificationHandling.registerWithFcm();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey,
navigatorObservers: <NavigatorObserver>[observer],
home: const HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Notify Demo')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('Allow notifications when prompted'),
// --- Temporary test buttons (Lecture 014) - remove before release ---
// FilledButton(
// onPressed: () {
// Future<void>.delayed(const Duration(milliseconds: 200), () {
// throw StateError('Real uncaught async crash');
// });
// },
// child: const Text('Throw async error'),
// ),
// OutlinedButton(
// onPressed: () => FirebaseCrashlytics.instance.crash(),
// child: const Text('Force native crash'),
// ),
],
),
),
);
}
}To actually test the two crash buttons: uncomment them, temporarily change
setCrashlyticsCollectionEnabled(!kDebugMode) to setCrashlyticsCollectionEnabled(true), run
with flutter run --release (not the debugger), tap a button, reopen the app, then check
Crashlytics in the Firebase console a few minutes later. Revert both changes afterward.