On this page12 sections
Lecture 011: Analytics Setup & Screen Tracking
| Category | 3: Analytics |
| Lecture | 011 of 014 |
| Estimated video length | 14 min |
| Target | Flutter 3.44 · Dart 3.12 · FlutterFire (latest) |
| Level | Intermediate |
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
flutter pub add firebase_analyticsThat'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_IDmeta-data in the manifest (it's read fromgoogle-services.json) or afirebase-analyticsdependency inbuild.gradle(the package adds it).FirebaseAppDelegateProxyEnabledinInfo.plististrueby 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:
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:
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:
# 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
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
- Name two events Analytics records with no code.
- What does
FirebaseAnalyticsObserverdo? - Why must routes have names?
- How do you see events within seconds?
Practice Answers
- Any two of
first_open,session_start,app_update. - Logs a
screen_viewevery time the navigator changes route. - The observer reports the route's name as the screen name.
- Turn on debug mode and open DebugView.
Key Takeaways
flutter pub add firebase_analyticsis all the setup Flutter needs.- Automatic events arrive without code.
FirebaseAnalyticsObserverinnavigatorObserverstracks 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
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')),
);
}
}