On this page13 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. logEvent
  4. 2. The Rules
  5. 3. Built-in Event Methods
  6. 4. Users
  7. Code Examples
  8. Common Beginner Mistakes
  9. Best Practices
  10. Practice Questions
  11. Practice Answers
  12. Key Takeaways
  13. Full Code (Copy-Paste Reference)

Lecture 012: Logging Custom Events

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

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 logEvent and 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

dart
await FirebaseAnalytics.instance.logEvent(
  name: 'promo_opened',
  parameters: {
    'promo_code': 'DART20',
    'discount_percent': 20,
    'datetime': DateTime.now().toIso8601String(),
  },
);

2. The Rules

Rule
Event nameletters, digits, _; starts with a letter; up to 40 characters
Reservedcan't start with firebase_, google_ or ga_; can't reuse automatic names like session_start
Parametersup to 25 per event; names follow the same rules
Parameter valuesString (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:

dart
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

dart
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

dart
// 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);
  }
}
dart
// 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 logEvent in one service class so names stay consistent.
  • Prefer built-in methods when one fits.

Practice Questions

  1. Which of these event names are valid: level_up, Level Up, firebase_test, 2nd_try?
  2. What value types can parameters have?
  3. Why use logLogin instead of logEvent(name: 'login')?
  4. What should you never put in a user ID?

Practice Answers

  1. Only level_up. Level Up has a space, firebase_ is reserved, 2nd_try starts with a digit.
  2. String and num.
  3. Built-in events feed Firebase's standard reports.
  4. 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 String or num.
  • 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

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

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'),
          ),
      ],
    );
  }
}