0
0
Fluttermobile~5 mins

Firebase Analytics in Flutter

Choose your learning style9 modes available
Introduction

Firebase Analytics helps you understand how people use your app. It tracks what users do so you can improve your app experience.

You want to know which buttons users tap the most.
You want to see how many users open your app each day.
You want to track when users complete a purchase.
You want to measure how long users stay in your app.
You want to find out which features are popular.
Syntax
Flutter
import 'package:firebase_analytics/firebase_analytics.dart';

FirebaseAnalytics analytics = FirebaseAnalytics.instance;

// Log an event
await analytics.logEvent(
  name: 'event_name',
  parameters: {'key': 'value'},
);

Use FirebaseAnalytics.instance to get the analytics object.

Events have a name and optional parameters to describe details.

Examples
Logs a simple event named 'button_click' without extra details.
Flutter
await analytics.logEvent(name: 'button_click');
Logs a 'purchase' event with details about the item and price.
Flutter
await analytics.logEvent(
  name: 'purchase',
  parameters: {'item': 'shoes', 'price': 59.99},
);
Sets a user ID to track events for a specific user.
Flutter
await analytics.setUserId(id: 'user123');
Sample App

This app initializes Firebase and shows a button. When pressed, it logs a 'button_pressed' event to Firebase Analytics and shows a message.

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(MyApp());
}

class MyApp extends StatelessWidget {
  final FirebaseAnalytics analytics = FirebaseAnalytics.instance;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Firebase Analytics Demo')),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              await analytics.logEvent(name: 'button_pressed');
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('Event logged!')),
              );
            },
            child: Text('Press me'),
          ),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Make sure to add Firebase to your Flutter project and configure it properly.

Events help you learn what users do, but avoid logging sensitive personal data.

You can view logged events in the Firebase Console under Analytics.

Summary

Firebase Analytics tracks user actions in your app.

Use logEvent to send events with names and details.

Check the Firebase Console to see how users interact with your app.