On this page12 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Add firebase_analytics
  4. 2. Screen Tracking with an Observer
  5. 3. DebugView: See It Live
  6. Code Examples
  7. Common Beginner Mistakes
  8. Best Practices
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways
  12. Full Code (Copy-Paste Reference)

Lecture 011: Analytics Setup & Screen Tracking

Category3: Analytics
Lecture011 of 014
Estimated video length14 min
TargetFlutter 3.44 · Dart 3.12 · FlutterFire (latest)
LevelIntermediate

Firebase Analytics shows how people use your app: how many, from where, which screens. We add it, track screens automatically with a navigator observer, and watch events live in DebugView.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Practice Questions · Answers · Takeaways · Full Code


Prerequisites

Lecture 004: Firebase initialized. Google Analytics enabled for the project (Lecture 001).


Learning Objectives

  • Add firebase_analytics
  • Know what Analytics collects with no extra code
  • Track screen views with FirebaseAnalyticsObserver
  • See events immediately in DebugView
  • Know which old setup steps aren't needed

1. Add firebase_analytics

bash
flutter pub add firebase_analytics

That's the whole native setup. As soon as Firebase starts, Analytics records automatic events: first_open, session_start, app_update, screen_view on iOS view controllers, plus device model, OS version and country.

Not needed in Flutter: a com.google.firebase.analytics.APP_ID meta-data in the manifest (it's read from google-services.json) or a firebase-analytics dependency in build.gradle (the package adds it). FirebaseAppDelegateProxyEnabled in Info.plist is true by default: leave it out unless you need to turn it off.

2. Screen Tracking with an Observer

Flutter screens are routes, which Analytics can't see by itself. A NavigatorObserver reports each route change as a screen_view:

dart
class _MyAppState extends State<MyApp> {
  static final FirebaseAnalytics analytics = FirebaseAnalytics.instance;
  static final FirebaseAnalyticsObserver observer =
      FirebaseAnalyticsObserver(analytics: analytics);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorObservers: <NavigatorObserver>[observer],
      // ...
    );
  }
}

The observer uses the route's name, so give routes names:

dart
Navigator.push(
  context,
  MaterialPageRoute(
    builder: (_) => const SettingsScreen(),
    settings: const RouteSettings(name: '/settings'),
  ),
);

Or use named routes: routes: {'/settings': (_) => const SettingsScreen()} with Navigator.pushNamed(context, '/settings').

3. DebugView: See It Live

Analytics normally batches events and the dashboard updates within hours. While developing, switch on debug mode to see events within seconds in Firebase console → Analytics → DebugView:

bash
# Android
adb shell setprop debug.firebase.analytics.app com.example.notify_demo
# turn it off again
adb shell setprop debug.firebase.analytics.app .none.

On iOS, in Xcode → Product → Scheme → Edit Scheme → Run → Arguments, add -FIRDebugEnabled.


Code Examples

Example 1: Two Tracked Screens

dart
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  static final FirebaseAnalytics analytics = FirebaseAnalytics.instance;
  static final FirebaseAnalyticsObserver observer =
      FirebaseAnalyticsObserver(analytics: analytics);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorObservers: <NavigatorObserver>[observer],
      initialRoute: '/',
      routes: {
        '/': (_) => const HomeScreen(),
        '/settings': (_) => const SettingsScreen(),
      },
    );
  }
}

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(title: const Text('Home')),
        body: Center(
          child: FilledButton(
            onPressed: () => Navigator.pushNamed(context, '/settings'),
            child: const Text('Open settings'),
          ),
        ),
      );
}

class SettingsScreen extends StatelessWidget {
  const SettingsScreen({super.key});

  @override
  Widget build(BuildContext context) =>
      Scaffold(appBar: AppBar(title: const Text('Settings')));
}

With debug mode on, open Settings and go back: DebugView shows screen_view events with firebase_screen: /settings, then /.


Common Beginner Mistakes

1. Unnamed routes: screens show up as null or not at all. Give every route a name.

2. Waiting for the dashboard: normal reports take hours. Use DebugView while developing.

3. Forgetting to turn debug mode off: it stays on for that device until you set .none..


Best Practices

  • Name routes consistently (/settings, /product/details).
  • Mention Analytics in your privacy policy; if you need consent first, use FirebaseAnalytics.instance.setAnalyticsCollectionEnabled(false) until the user agrees.
  • Keep the observer in one place: the root MaterialApp.

Practice Questions

  1. Name two events Analytics records with no code.
  2. What does FirebaseAnalyticsObserver do?
  3. Why must routes have names?
  4. How do you see events within seconds?

Practice Answers

  1. Any two of first_open, session_start, app_update.
  2. Logs a screen_view every time the navigator changes route.
  3. The observer reports the route's name as the screen name.
  4. Turn on debug mode and open DebugView.

Key Takeaways

  • flutter pub add firebase_analytics is all the setup Flutter needs.
  • Automatic events arrive without code.
  • FirebaseAnalyticsObserver in navigatorObservers tracks named routes as screens.
  • DebugView shows events live while developing.

Full Code (Copy-Paste Reference)

Everything the app needs up to and including this lecture. Only main.dart changes: it gains the analytics observer alongside everything messaging already set up. firebase_notification_handling.dart, dialog_promo_code.dart and notification_status.dart are unchanged from Lecture 009.

lib/main.dart

dart
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.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);
  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>();

  // One analytics instance + one observer, shared by the whole app.
  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,
      // The observer reports a screen_view on every route change - give any
      // route you push a RouteSettings name so it shows up correctly.
      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: const Center(child: Text('Allow notifications when prompted')),
    );
  }
}