Firebase Crashlytics and Analytics in Flutter: solved exercise

Firebase Crashlytics and Analytics in Flutter: solved exercise

Crashlytics automatically records your app’s crashes and groups them by cause. Analytics collects user behavior events. Together they form the observability baseline for any production app.

Problem statement

Integrate Firebase Crashlytics and Analytics in a Flutter app that:

  • Records crashes and non-fatal errors with context (keys, logs).
  • Triggers a test crash from the UI.
  • Records custom Analytics events.
  • Automatically tracks the current screen on navigation.
  • Identifies the authenticated user in Crashlytics.

Dependencies

1
2
3
4
dependencies:
  firebase_core: ^3.13.0
  firebase_crashlytics: ^4.3.3
  firebase_analytics: ^11.4.4

Initialize Firebase with the FlutterFire CLI:

1
2
flutter pub add firebase_core firebase_crashlytics firebase_analytics
flutterfire configure

Full solution

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import 'dart:async';
import 'package:firebase_analytics/firebase_analytics.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';

// ── Observability service ──────────────────────────────────────────────────────
class ObservabilityService {
  static final _crashlytics = FirebaseCrashlytics.instance;
  static final _analytics = FirebaseAnalytics.instance;

  static Future<void> initialize() async {
    // Pass all Flutter errors to Crashlytics
    FlutterError.onError = _crashlytics.recordFlutterFatalError;

    // Capture async errors outside the widget tree
    PlatformDispatcher.instance.onError = (error, stack) {
      _crashlytics.recordError(error, stack, fatal: true);
      return true;
    };

    // Disable Crashlytics in debug (only active in release)
    await _crashlytics.setCrashlyticsCollectionEnabled(!kDebugMode);
  }

  // ── Crashlytics ──────────────────────────────────────────────────────────────

  static Future<void> setUser({required String userId, String? email}) async {
    await _crashlytics.setUserIdentifier(userId);
    await _crashlytics.setCustomKey('user_email', email ?? 'unknown');
  }

  static Future<void> setContext(String key, String value) =>
      _crashlytics.setCustomKey(key, value);

  static void log(String message) => _crashlytics.log(message);

  static Future<void> recordError(
    Object error,
    StackTrace? stack, {
    String? reason,
    bool fatal = false,
  }) =>
      _crashlytics.recordError(error, stack, reason: reason, fatal: fatal);

  // ── Analytics ────────────────────────────────────────────────────────────────

  static Future<void> setCurrentScreen(String screenName) =>
      _analytics.setCurrentScreen(screenName: screenName);

  static Future<void> logProductView({
    required String productId,
    required String productName,
    required double price,
  }) =>
      _analytics.logViewItem(
        items: [
          AnalyticsEventItem(
            itemId: productId,
            itemName: productName,
            price: price,
          )
        ],
      );

  static Future<void> logPurchase({
    required String transactionId,
    required double value,
    required String currency,
  }) =>
      _analytics.logPurchase(
        transactionId: transactionId,
        value: value,
        currency: currency,
      );

  static Future<void> logEvent(
    String name, {
    Map<String, Object>? parameters,
  }) =>
      _analytics.logEvent(name: name, parameters: parameters);

  static Future<void> setUserProperty({
    required String name,
    required String value,
  }) =>
      _analytics.setUserProperty(name: name, value: value);
}

// ── Main ───────────────────────────────────────────────────────────────────────
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  runZonedGuarded(
    () async {
      await Firebase.initializeApp();
      await ObservabilityService.initialize();

      await ObservabilityService.setUser(
        userId: 'user_12345',
        email: 'demo@flutter.dev',
      );

      runApp(const CrashlyticsDemo());
    },
    (error, stack) {
      FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
    },
  );
}

// ── App ────────────────────────────────────────────────────────────────────────
class CrashlyticsDemo extends StatelessWidget {
  const CrashlyticsDemo({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Crashlytics + Analytics',
      navigatorObservers: [
        FirebaseAnalyticsObserver(analytics: FirebaseAnalytics.instance),
      ],
      home: const HomePage(),
    );
  }
}

// ── Home screen ────────────────────────────────────────────────────────────────
class HomePage extends StatefulWidget {
  const HomePage({super.key});
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final _logs = <String>[];

  @override
  void initState() {
    super.initState();
    ObservabilityService.setCurrentScreen('home');
    ObservabilityService.log('HomePage mounted');
  }

  void _addLog(String msg) =>
      setState(() => _logs.insert(0,
          '${DateTime.now().toIso8601String().substring(11, 19)} $msg'));

  Future<void> _testCrash() async {
    ObservabilityService.log('User taps test crash button');
    await ObservabilityService.setContext('last_action', 'test_crash');
    // In release this sends the crash to Crashlytics and closes the app
    FirebaseCrashlytics.instance.crash();
    _addLog('Test crash sent');
  }

  Future<void> _logNonFatal() async {
    try {
      throw StateError('Invalid state while processing order #42');
    } catch (e, stack) {
      await ObservabilityService.recordError(
        e,
        stack,
        reason: 'Error processing order at checkout',
        fatal: false,
      );
      _addLog('Non-fatal error recorded in Crashlytics');
    }
  }

  Future<void> _logProductView() async {
    await ObservabilityService.logProductView(
      productId: 'book_flutter_001',
      productName: 'Flutter in Depth',
      price: 29.99,
    );
    _addLog('Analytics: view_item recorded');
  }

  Future<void> _logPurchase() async {
    await ObservabilityService.logPurchase(
      transactionId: 'txn_${DateTime.now().millisecondsSinceEpoch}',
      value: 29.99,
      currency: 'USD',
    );
    _addLog('Analytics: purchase recorded');
  }

  Future<void> _logCustomEvent() async {
    await ObservabilityService.logEvent(
      'tutorial_complete',
      parameters: {
        'tutorial_id': 'flutter_basics',
        'success': true,
      },
    );
    _addLog('Analytics: tutorial_complete recorded');
  }

  Future<void> _setUserProperty() async {
    await ObservabilityService.setUserProperty(
      name: 'subscription_plan',
      value: 'premium',
    );
    _addLog('Analytics: user property subscription_plan=premium');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Crashlytics + Analytics')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text('Crashlytics',
                style: Theme.of(context).textTheme.titleMedium
                    ?.copyWith(color: Theme.of(context).colorScheme.primary)),
            const SizedBox(height: 8),
            FilledButton.icon(
              onPressed: _logNonFatal,
              icon: const Icon(Icons.warning_amber),
              label: const Text('Record non-fatal error'),
              style: FilledButton.styleFrom(backgroundColor: Colors.orange),
            ),
            const SizedBox(height: 4),
            OutlinedButton.icon(
              onPressed: _testCrash,
              icon: const Icon(Icons.dangerous),
              label: const Text('Test crash (release only)'),
              style: OutlinedButton.styleFrom(foregroundColor: Colors.red),
            ),

            const Divider(height: 24),

            Text('Analytics',
                style: Theme.of(context).textTheme.titleMedium
                    ?.copyWith(color: Theme.of(context).colorScheme.primary)),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                FilledButton.tonal(
                    onPressed: _logProductView,
                    child: const Text('view_item')),
                FilledButton.tonal(
                    onPressed: _logPurchase,
                    child: const Text('purchase')),
                FilledButton.tonal(
                    onPressed: _logCustomEvent,
                    child: const Text('tutorial_complete')),
                FilledButton.tonal(
                    onPressed: _setUserProperty,
                    child: const Text('user property')),
              ],
            ),

            const Divider(height: 24),

            Text('Local log:', style: Theme.of(context).textTheme.labelLarge),
            const SizedBox(height: 8),
            Expanded(
              child: _logs.isEmpty
                  ? const Center(
                      child: Text('Tap a button to record an event',
                          style: TextStyle(color: Colors.grey)))
                  : ListView.builder(
                      itemCount: _logs.length,
                      itemBuilder: (_, i) => Text(_logs[i],
                          style: const TextStyle(
                              fontSize: 12, fontFamily: 'monospace')),
                    ),
            ),
          ],
        ),
      ),
    );
  }
}

Data Crashlytics captures automatically

DataSource
Stack traceFlutterError.onError + PlatformDispatcher.onError
App versionpubspec.yaml version
Device and OSFirebase SDK
Custom keyssetCustomKey
Logslog() (last 64 KB)
UsersetUserIdentifier

Common mistakes

  • Crashes don’t appear in Firebase console: Crashlytics only sends reports in release mode. In debug, use kDebugMode to avoid collisions. Also wait up to 5 minutes for them to appear.
  • Forgetting runZonedGuarded: async errors that occur outside the widget tree (timers, isolates) are not captured by FlutterError.onError. runZonedGuarded captures them all.
  • Sending PII to Analytics: Analytics events must not include names, emails, or plain IDs. Use anonymized IDs and call setAnalyticsCollectionEnabled(false) when the user rejects consent.

Practical use

Crashlytics + Analytics are the minimum observability for any production app. Complement with Firebase Performance to measure network response times and rendering.

Guided practice and next step

FAQ

Can I use Crashlytics without Analytics?

Yes. They are independent packages even though they are complementary. You can install only firebase_crashlytics if you don’t need Analytics.

How do I test that Crashlytics works without publishing the app?

Use FirebaseCrashlytics.instance.crash() in a local release build (flutter build apk --release). Open the app, tap the button, and within a few minutes you’ll see the crash in the Firebase console.

Can I comply with GDPR using Firebase Analytics?

Yes. Disable collection with setAnalyticsCollectionEnabled(false) until the user accepts consent. Use resetAnalyticsData() if the user revokes consent.