On this page13 sections
Lecture 012: Logging Custom Events
| Category | 3: Analytics |
| Lecture | 012 of 014 |
| Estimated video length | 14 min |
| Target | Flutter 3.44 · Dart 3.12 · FlutterFire (latest) |
| Level | Intermediate |
Automatic events tell you that people use the app. Custom events tell you what they do: which button, which product, which level. We log them with parameters and follow the naming rules.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Practice Questions · Answers · Takeaways · Full Code
Prerequisites
Lecture 011: Analytics added, DebugView working.
Learning Objectives
- Log events with
logEventand parameters - Follow the naming and type rules
- Use the built-in event methods
- Set a user ID and user properties
- Wrap Analytics in a small service class
1. logEvent
await FirebaseAnalytics.instance.logEvent(
name: 'promo_opened',
parameters: {
'promo_code': 'DART20',
'discount_percent': 20,
'datetime': DateTime.now().toIso8601String(),
},
);2. The Rules
| Rule | |
|---|---|
| Event name | letters, digits, _; starts with a letter; up to 40 characters |
| Reserved | can't start with firebase_, google_ or ga_; can't reuse automatic names like session_start |
| Parameters | up to 25 per event; names follow the same rules |
| Parameter values | String (up to 100 characters) or num: not bool, List or Map |
Style: snake_case, promo_opened, not PromoOpened or Promo Opened. Names are
case-sensitive, so PromoOpened and promo_opened count as two different events.
Booleans: send 'true'/'false' as strings, or 1/0.
3. Built-in Event Methods
For common actions, use the ready-made methods: Firebase understands these and shows them in special reports:
final analytics = FirebaseAnalytics.instance;
await analytics.logLogin(loginMethod: 'email');
await analytics.logSignUp(signUpMethod: 'google');
await analytics.logSearch(searchTerm: 'dart course');
await analytics.logShare(contentType: 'lecture', itemId: '012', method: 'whatsapp');
await analytics.logScreenView(screenName: 'Checkout');4. Users
await analytics.setUserId(id: 'user_123'); // your own ID, never an email
await analytics.setUserProperty(name: 'plan', value: 'pro');User properties let you split reports: for example "events from pro users".
Code Examples
Example 1: An Analytics Service
// 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);
}
}// In the promo dialog from Lecture 007:
FilledButton(
onPressed: () {
AnalyticsService.promoOpened('DART20', 20);
Navigator.pop(context);
},
child: const Text('Use code'),
)Tap the button with debug mode on: DebugView shows promo_opened with promo_code: DART20 and
discount_percent: 20.
Example 2: Seeing Parameters in Reports
Parameters appear in DebugView straight away. To use them in the normal Events reports, go to
Analytics → Custom definitions → Create custom dimension, pick the parameter
(promo_code), scope Event. Reports include it from then on (not retroactively).
Common Beginner Mistakes
1. Spaces or dashes in names: promo-opened or Promo Opened is dropped silently. Use
snake_case.
2. Passing a bool: {'success': true} throws. Send 'true' or 1.
3. Logging personal data: emails, phone numbers or names in events break Google's policy and your users' trust. Use IDs.
Best Practices
- Plan a short list of events before coding: what questions should the data answer?
- Keep every
logEventin one service class so names stay consistent. - Prefer built-in methods when one fits.
Practice Questions
- Which of these event names are valid:
level_up,Level Up,firebase_test,2nd_try? - What value types can parameters have?
- Why use
logLogininstead oflogEvent(name: 'login')? - What should you never put in a user ID?
Practice Answers
- Only
level_up.Level Uphas a space,firebase_is reserved,2nd_trystarts with a digit. Stringandnum.- Built-in events feed Firebase's standard reports.
- Personal data such as an email or phone number.
Key Takeaways
logEvent(name, parameters)records what users do.- snake_case names, ≤ 40 characters; values are
Stringornum. - Built-in methods (
logLogin,logSearch, …) power standard reports. - Register custom dimensions to see parameters in reports; never log personal data.
Full Code (Copy-Paste Reference)
Everything the app needs up to and including this lecture, file by file. main.dart,
firebase_notification_handling.dart and notification_status.dart are unchanged from
Lecture 011.
lib/analytics_service.dart
import 'package:firebase_analytics/firebase_analytics.dart';
// Every logEvent call for the app goes through here - one place to keep
// event names and parameter keys consistent (and spelled correctly).
class AnalyticsService {
static final FirebaseAnalytics _analytics = FirebaseAnalytics.instance;
static Future<void> promoOpened(String code, int percent) {
return _analytics.logEvent(
name: 'promo_opened', // snake_case, not reserved, under 40 chars
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) {
// Prefer the built-in method when one exists - it feeds Firebase's standard reports.
return _analytics.logLogin(loginMethod: method);
}
}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: () {
// Logged BEFORE popping, while the data is still at hand.
AnalyticsService.promoOpened(promoCode, discountPercent);
Navigator.pop(context);
},
child: const Text('Use code'),
),
],
);
}
}