Firebase Analytics & Custom Events
Firebase Analytics & Custom Events
Firebase Analytics (now called Google Analytics for Firebase) is a free, unlimited analytics solution built into the Firebase ecosystem. It automatically collects dozens of events — such as app opens, session starts, and first opens — and lets you define custom events that match your app's unique user journeys. In this lesson you will integrate the firebase_analytics package, log both automatic and custom events, set user properties, and verify delivery in Firebase DebugView and the Analytics dashboard.
1. Adding the Dependency
Add firebase_analytics to your pubspec.yaml alongside your existing Firebase packages:
# pubspec.yaml
dependencies:
flutter:
sdk: flutter
firebase_core: ^3.6.0
firebase_analytics: ^11.3.3
Run flutter pub get, then re-run flutterfire configure if you added a new platform. No additional native setup is needed — FlutterFire handles registration automatically.
2. Initialising FirebaseAnalytics
Create a single FirebaseAnalytics instance after Firebase.initializeApp(). Expose it through your dependency injection layer or pass it down as needed:
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Obtain the singleton instance
final analytics = FirebaseAnalytics.instance;
// Attach the observer so screen-view events fire automatically
runApp(MyApp(analytics: analytics));
}
class MyApp extends StatelessWidget {
final FirebaseAnalytics analytics;
const MyApp({super.key, required this.analytics});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Analytics Demo',
navigatorObservers: [
FirebaseAnalyticsObserver(analytics: analytics),
],
home: const HomeScreen(),
);
}
}
FirebaseAnalyticsObserver to MaterialApp.navigatorObservers automatically logs a screen_view event every time a named route is pushed or popped, with no extra code required per screen.3. Logging Automatic vs Custom Events
Firebase Analytics pre-defines automatic events (e.g. app_open, session_start, first_open) that are collected with zero code. For business-specific behaviour you log custom events via logEvent().
The SDK also provides strongly-typed convenience methods for common e-commerce and engagement events:
class AnalyticsService {
final FirebaseAnalytics _analytics = FirebaseAnalytics.instance;
// --- Predefined event helpers ---
Future<void> logLogin({required String method}) =>
_analytics.logLogin(loginMethod: method);
Future<void> logSignUp({required String method}) =>
_analytics.logSignUp(signUpMethod: method);
Future<void> logSearch({required String term}) =>
_analytics.logSearch(searchTerm: term);
Future<void> logShare({
required String contentType,
required String itemId,
required String method,
}) =>
_analytics.logShare(
contentType: contentType,
itemId: itemId,
method: method,
);
// --- Custom event ---
Future<void> logCourseEnrolled({
required String courseId,
required String courseName,
required String level,
}) =>
_analytics.logEvent(
name: 'course_enrolled', // snake_case, max 40 chars
parameters: <String, Object>{
'course_id': courseId, // String (max 100 chars)
'course_name': courseName,
'level': level,
'timestamp': DateTime.now().millisecondsSinceEpoch,
},
);
Future<void> logLessonCompleted({
required String lessonId,
required int durationSeconds,
required int score,
}) =>
_analytics.logEvent(
name: 'lesson_completed',
parameters: <String, Object>{
'lesson_id': lessonId,
'duration_seconds': durationSeconds, // int or double
'score': score,
'passed': score >= 70, // bool is cast to int (1/0)
},
);
}
Naming constraints to remember:
- Event names: snake_case, max 40 characters, must start with a letter.
- Parameter names: max 40 characters; values can be
String,int, ordouble. - Max 25 parameters per event. Excess parameters are silently dropped.
- Do not use reserved prefixes:
firebase_,google_, orga_.
4. Setting User Properties
User properties are attributes that describe segments of your user base, such as subscription tier, preferred language, or account type. Unlike events (which fire once per action), a user property persists across sessions until you overwrite it:
Future<void> setUserProperties({
required String userId,
required String plan,
required String preferredLanguage,
}) async {
final analytics = FirebaseAnalytics.instance;
// Associate events with an internal user ID (hashed — never PII)
await analytics.setUserId(id: userId);
// Custom user properties (max 25 per project, 24-char name, 36-char value)
await analytics.setUserProperty(name: 'subscription_plan', value: plan);
await analytics.setUserProperty(
name: 'preferred_language',
value: preferredLanguage,
);
}
setUserId or setUserProperty. Firebase Terms of Service prohibit this. Always use an internal, non-reversible identifier.5. Verifying Events with DebugView
By default, Analytics batches events and uploads them every ~60 seconds. During development, enable DebugView mode so events appear in the Firebase Console within seconds:
- Android: Run
adb shell setprop debug.firebase.analytics.app <YOUR_PACKAGE_NAME>from your terminal. - iOS: Add
-FIRAnalyticsDebugEnabledto the scheme's launch arguments in Xcode. - Open Firebase Console → Analytics → DebugView and select your device from the dropdown.
Each event card shows its name, timestamp, and parameter values. Verify your custom events fire with the correct parameter keys and values before releasing.
6. Summary
In this lesson you learned how to integrate Firebase Analytics into a Flutter app end-to-end: adding the dependency, initialising the singleton, attaching the navigator observer for automatic screen-view events, logging predefined and custom events with typed parameters, setting persistent user properties, and verifying delivery in DebugView. These analytics signals are the foundation for data-driven decisions — you can now create audiences, conversion funnels, and A/B tests directly in the Firebase and Google Analytics consoles.