Bird
Raised Fist0
Fluttermobile~20 mins

Firebase Analytics in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Analytics Demo Screen
This screen logs a custom event to Firebase Analytics when a button is pressed and shows a confirmation message.
Target UI
┌───────────────────────────────┐
│       Analytics Demo          │
├───────────────────────────────┤
│                               │
│   [ Log Custom Event ]         │
│                               │
└───────────────────────────────┘
Add a button labeled 'Log Custom Event'.
When the button is pressed, log a custom event named 'button_pressed' with a parameter 'button_name' set to 'Log Custom Event'.
Show a SnackBar confirming the event was logged.
Initialize Firebase Analytics properly.
Starter Code
Flutter
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_analytics/firebase_analytics.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Firebase Analytics Demo',
      home: const AnalyticsDemoScreen(),
    );
  }
}

class AnalyticsDemoScreen extends StatefulWidget {
  const AnalyticsDemoScreen({super.key});

  @override
  State<AnalyticsDemoScreen> createState() => _AnalyticsDemoScreenState();
}

class _AnalyticsDemoScreenState extends State<AnalyticsDemoScreen> {
  final FirebaseAnalytics analytics = FirebaseAnalytics.instance;

  void _logCustomEvent() {
    // TODO: Log custom event and show SnackBar
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Analytics Demo')),
      body: Center(
        child: ElevatedButton(
          onPressed: _logCustomEvent,
          child: const Text('Log Custom Event'),
        ),
      ),
    );
  }
}
Task 1
Task 2
Solution
Flutter
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_analytics/firebase_analytics.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Firebase Analytics Demo',
      home: const AnalyticsDemoScreen(),
    );
  }
}

class AnalyticsDemoScreen extends StatefulWidget {
  const AnalyticsDemoScreen({super.key});

  @override
  State<AnalyticsDemoScreen> createState() => _AnalyticsDemoScreenState();
}

class _AnalyticsDemoScreenState extends State<AnalyticsDemoScreen> {
  final FirebaseAnalytics analytics = FirebaseAnalytics.instance;

  void _logCustomEvent() async {
    await analytics.logEvent(
      name: 'button_pressed',
      parameters: {'button_name': 'Log Custom Event'},
    );
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Custom event logged!')),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Analytics Demo')),
      body: Center(
        child: ElevatedButton(
          onPressed: _logCustomEvent,
          child: const Text('Log Custom Event'),
        ),
      ),
    );
  }
}

This Flutter app initializes Firebase and uses Firebase Analytics to log a custom event when the user taps the button labeled Log Custom Event. The _logCustomEvent method calls analytics.logEvent with the event name button_pressed and a parameter button_name. After logging, it shows a SnackBar to confirm the event was sent. This helps track user interactions in your app easily.

Final Result
Completed Screen
┌───────────────────────────────┐
│       Analytics Demo          │
├───────────────────────────────┤
│                               │
│   [ Log Custom Event ]         │
│                               │
└───────────────────────────────┘
When the user taps the 'Log Custom Event' button, a custom event 'button_pressed' is sent to Firebase Analytics.
A SnackBar appears at the bottom with the message 'Custom event logged!'.
Stretch Goal
Add a second button that logs a 'screen_view' event with the screen name 'AnalyticsDemoScreen'.
💡 Hint
Use analytics.logScreenView(screenName: 'AnalyticsDemoScreen') inside the button's onPressed callback.

Practice

(1/5)
1. What is the main purpose of Firebase Analytics in a Flutter app?
easy
A. To create user interface layouts
B. To manage app navigation between screens
C. To track user actions and events within the app
D. To store user data locally on the device

Solution

  1. Step 1: Understand Firebase Analytics role

    Firebase Analytics is designed to collect data about user interactions and events in the app.
  2. Step 2: Compare options with purpose

    Only To track user actions and events within the app describes tracking user actions, which matches Firebase Analytics' main use.
  3. Final Answer:

    To track user actions and events within the app -> Option C
  4. Quick Check:

    Firebase Analytics = Track user actions [OK]
Hint: Firebase Analytics tracks events, not UI or storage [OK]
Common Mistakes:
  • Confusing analytics with UI design
  • Thinking it manages navigation
  • Assuming it stores data locally
2. Which is the correct way to log a custom event named 'purchase' with Firebase Analytics in Flutter?
easy
A. logEvent('purchase');
B. FirebaseAnalytics.logEvent('purchase');
C. FirebaseAnalytics.log('purchase');
D. FirebaseAnalytics.instance.logEvent(name: 'purchase');

Solution

  1. Step 1: Recall Firebase Analytics method syntax

    The correct method to log events is logEvent with named parameter 'name'.
  2. Step 2: Check each option's syntax

    FirebaseAnalytics.instance.logEvent(name: 'purchase'); uses FirebaseAnalytics.instance and calls logEvent(name: 'purchase'), which is correct.
  3. Final Answer:

    FirebaseAnalytics.instance.logEvent(name: 'purchase'); -> Option D
  4. Quick Check:

    Use logEvent(name: 'eventName') method [OK]
Hint: Use instance and named 'name' parameter for logEvent [OK]
Common Mistakes:
  • Calling logEvent without instance
  • Missing named parameter 'name'
  • Using wrong method names
3. What will happen when this Flutter code runs?
FirebaseAnalytics analytics = FirebaseAnalytics.instance;
await analytics.logEvent(name: 'button_click', parameters: {'button': 'play'});
medium
A. Throws a syntax error due to missing semicolon
B. Logs an event named 'button_click' with parameter 'button' set to 'play'
C. Navigates to a new screen named 'button_click'
D. Stores the parameter locally without sending to Firebase

Solution

  1. Step 1: Analyze the code's function call

    The code creates an analytics instance and calls logEvent with name and parameters.
  2. Step 2: Understand logEvent behavior

    logEvent sends the event data to Firebase Analytics backend for tracking.
  3. Final Answer:

    Logs an event named 'button_click' with parameter 'button' set to 'play' -> Option B
  4. Quick Check:

    logEvent sends named event with parameters [OK]
Hint: logEvent sends event data to Firebase, not UI or local storage [OK]
Common Mistakes:
  • Thinking it causes navigation
  • Assuming it stores data locally only
  • Confusing syntax errors
4. Identify the error in this Flutter Firebase Analytics code:
FirebaseAnalytics analytics = FirebaseAnalytics.instance;
analytics.logEvent('login');
medium
A. logEvent requires named parameter 'name', not a positional argument
B. FirebaseAnalytics cannot be instantiated directly
C. logEvent method does not exist
D. Missing await keyword before logEvent

Solution

  1. Step 1: Check logEvent method signature

    logEvent requires a named parameter 'name', so passing a positional argument is incorrect.
  2. Step 2: Verify other options

    FirebaseAnalytics can be instantiated, logEvent exists, and await is optional but recommended.
  3. Final Answer:

    logEvent requires named parameter 'name', not a positional argument -> Option A
  4. Quick Check:

    logEvent(name: 'eventName') syntax needed [OK]
Hint: logEvent needs named 'name' parameter, not just a string [OK]
Common Mistakes:
  • Passing event name as positional argument
  • Forgetting named parameters
  • Confusing method existence
5. You want to track when a user completes a level in your game with level number and score. Which is the best way to log this event using Firebase Analytics in Flutter?
hard
A. analytics.logEvent(name: 'level_complete', parameters: {'level': levelNumber, 'score': score});
B. analytics.logEvent('level_complete', {'level': levelNumber, 'score': score});
C. analytics.logEvent(name: 'levelComplete', level: levelNumber, score: score);
D. analytics.logEvent('levelComplete', levelNumber, score);

Solution

  1. Step 1: Use correct method signature for logEvent

    logEvent requires a named 'name' parameter and an optional 'parameters' map.
  2. Step 2: Check parameter passing style

    analytics.logEvent(name: 'level_complete', parameters: {'level': levelNumber, 'score': score}); correctly uses name and parameters map with keys and values for level and score.
  3. Step 3: Identify errors in other options

    Options B, C, and D use incorrect syntax or parameter passing styles.
  4. Final Answer:

    analytics.logEvent(name: 'level_complete', parameters: {'level': levelNumber, 'score': score}); -> Option A
  5. Quick Check:

    Use named 'name' and 'parameters' map for event data [OK]
Hint: Always use named 'name' and 'parameters' map for event details [OK]
Common Mistakes:
  • Passing event name as positional argument
  • Not using parameters map
  • Incorrect parameter names
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard