0
0
Fluttermobile~20 mins

Firebase Analytics in Flutter - Mini App: Build & Ship

Choose your learning style9 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.