Flutter - Using Firebase Analytics

This tutorial shows you how to use Firebase Analytics in Flutter.

If you have an application with a lot of users, tracking how the users use the application is very important. If you know the behavior of the users, you can determine what to do to improve the application. To do so, you need to track the user data and particular events that occur in the application. After that, you need to generate a report to be used for data analytics.

You can develop your own service for doing that. But for quick solutions, you can use a 3rd party analytics service. One of which is Firebase Analytics. With the help of the official plugin for Flutter, it can automatically track several user properties and events which reduces development effort. It also allows you to define custom user properties and events other than those predefined or suggested by Firebase. Therefore, you can track anything that you want. The usage is also quite simple and it already has a reporting feature that you can access from the Firebase Console.

Integrate Firebase to Flutter Application

Like using other Firebase services, you need to integrate your Firebase account with your Flutter application. Basically, what you need to do is create a Firebase project and add application(s) to the Firebase project. Then, download and copy the config files to your Flutter project. You can read the details in our tutorial about integration with Firebase services in Flutter.

To use Analytics in a Flutter application, you can use the firebase_analytics package. Add the below dependency to your pubspec.yaml file and run flutter pub get.

  dependencies:
    firebase_analytics: ^8.0.4

Dimension and Metric

First of all, you need to understand about dimension and metric in Firebase. In the Firebase Console, open the AnalyticsCustom Dimensions from the sidebar. On the opened page, you should see two tabs: Custom dimensions and Custom metrics.

The term dimension in Firebase Analytics usually refers to the detail about a user (or the used device) or an event. For example, user preference, favorite item, page title, or transaction ID. Firebase has some predefined dimensions, you can read the list here. You can also create your own dimensions

To create a custom metric, open the Custom dimensions tab and click the Create custom dimensions button. In the form, you need to fill in the name and the description. For the scope, you should choose whether it's related to user or event. You also need to fill in the event parameter or the user parameter, according to the scope that you choose. If the application logs an event or sets a user property with the matching parameter, it will be supplied to the defintion.

In this tutorial, we are going to create a new custom dimension named Favorite Item whose event parameter is favorite_item and scope type is User.

Firebase Analytics - New Custom Dimension - User

And another custom dimension named Item ID whose event parameter is item_id and scope type is Event.

Firebase Analytics - New Custom Dimension - Event

Another term you need to know is metric. The main difference between dimension and metric is that a metric has a unit of measurement. That enables Firebase to show the sum and average values for the metric in the report.

To create a custom metric, open the Custom metrics tab and click the Create custom metrics button. There will be a form where you need to enter the name, description, event parameter, and unit of measurement for the metric. In this tutorial, we are going to create a custom metric named Special Purchase whose event parameter is special_purchase_amount.

Firebase Analytics - New Custom Metric

The custom dimensions and custom metrics are related to setting custom user properties and logging custom events. To set a custom user property, you have to use the user parameter that you enter when creating a custom dimension as the reference. For logging a custom event, you can add some parameters. For each parameter, you have to use the event parameter that you enter when creating a custom dimension or a custom metric.

Using Firebase Analytics in Flutter

The Firebase Analytics can be used to track many things, such as page transition, user properties, and events. First, you need to get the FirebaseAnalytics instance. After adding firebase_analytics as a dependency and running flutter pub get, you need to import the plugin on the file where you want to use it.

  import 'package:firebase_analytics/firebase_analytics.dart';

Then, you can call the constructor to get the instance.

  final FirebaseAnalytics firebaseAnalytics = FirebaseAnalytics();

Track Page Transitions

MaterialApp has an argument named navigatorObservers for which you can pass a List of NavigatorObservers. To track page transitions using Firebase Analytics, you can pass a FirebaseAnalyticsObserver as one of the NavigatorObservers.

You need to add another import to use the observer.

  import 'package:firebase_analytics/observer.dart';

After that, call the constructor of FirebaseAnalyticsObserver and pass the FirebaseAnalytics instance. Below is an example of how to pass FirebaseAnalyticsObserver as the navigatorObservers argument.

    MaterialApp(
    navigatorObservers: [
      FirebaseAnalyticsObserver(analytics: FirebaseAnalytics()),
    ],
    // other arguments
  )

Set User ID

To set the user ID property, you can use the setUserId method. It makes it possible to associate the same user ID for the same user across multiple apps, multiple devices, or multiple analytics providers. Firebase has a guideline about the value you should use for user ID. For example, you should not use a value that a 3rd party can use to identify the user (e.g. a user's email or phone number).

  Future<void> setUserId(String? id)

Example:

   await _firebaseAnalytics.setUserId('000001');

Set User Properties

Automatically Logged Properties

Firebase Analytics automatically logs some properties. You can read the details here. For those properties, you don't need to manually set the values.

Custom User Properties

As I have explained above, you can define a new user property when creating a new custom dimension whose scope is user. For a custom user property, you need to manually set the value. Setting the value of a user property is quite simple. You need to call the setUserProperty and pass the name and the value of the property as name and value arguments respectively.

  Future<void> setUserProperty({
    required String name,
    required String? value
  })

Example:

  await _firebaseAnalytics.setUserProperty(
    name: 'favorite_color',
    value: 'pink',
  );

At the time this post was written, there was no way to get the list of values for a user property. In order to know whether a custom user property is successfully set, you can open AnalyticsDashboard page. Then, try to add a filter for the property. You may need to have some different users (or different Firebase installation IDs) set the custom property before you can filter the property (at least 10). Otherwise, the applied filter may return an empty result.

Track Events

Automatically Logged Events

There are some events that are logged automatically by Firebase, such as first_open, app_update. You do not need to manually log those events. For the list of events that are automatically logged, you can read the documentation here.

Suggested Events

Firebase has some suggested events and you need to log them manually. The plugin provides several methods for logging the suggested events. For example, you can use the logAppOpen to track the event when a user opens the application.

 await  _firebaseAnalytics.logAppOpen();

Below is the list of methods for logging the suggested events along with the event name in the bracket:

  • logAddPaymentInfo (add_payment_info)
  • logAddToCart (add_to_cart)
  • logAddToWishlist (add_to_wishlist)
  • logAppOpen (app_open)
  • logBeginCheckout (begin_checkout)
  • logCampaignDetails (campaign_details)
  • logEarnVirtualCurrency (earn_virtual_currency)
  • logEcommercePurchase (ecommerce_purchase)
  • logGenerateLead (generate_lead)
  • logJoinGroup (join_group)
  • logLevelUp (level_up)
  • logLevelStart (level_start)
  • logLevelEnd (level_end)
  • logLogin (login)
  • logPostScore (post_score)
  • logPresentOffer (present_offer)
  • logSearch (search)
  • logSelectContent (select_content)
  • logSetCheckoutOption (set_checkout_option)
  • logShare (share)
  • logSignUp (sign_up)
  • logSpendVirtualCurrency (spend_virtual_currency)
  • logTutorialBegin (tutorial_begin)
  • logTutorialComplete (tutorial_complete)
  • logUnlockAchievement (unlock_achievement)
  • logViewItem (view_item)
  • logViewItemList (view_item_list)
  • logViewSearchResults (view_search_results)

Custom Events

For logging custom events, you can use the logEvent method.

  Future<void> logEvent({
    required String name,
    Map<String, Object?>? parameters
  })

For the name argument, you need to pass the event name which can only contain alphanumeric characters and underscores, with an alphabetic as the first character. The maximum length is 40. You are not allowed to use reserved prefixes (firebase_, google_, ga_) or reserved events which can be seen on Firebase Event documentation.

For the parameters argument, you can optionally pass a Map which contains the parameters related to the event. For each element of the Map, the key is the event parameter that you input when creating a custom dimension or a custom metric, while the value's type may vary for each parameter.

  await _firebaseAnalytics.logEvent(
    name: 'special_purchase',
    parameters: {
      'special_purchase_amount': 100,
      'item_id': 'item-001',
    },
  );

The report for events can be seen on the AnalyticsEvents page. If the event is new, you need to log that event a few times (at least 10) and wait for several hours before being shown in the event list. Below is a report example for the special_purchase event. As you can see, there is a section that shows the Special Purchase metric. That's because we add the special_purchase_amount parameter (which is the event parameter of Special Purchase metric) when logging the special_purhcase event. In addition, there is a section for the Item ID dimension which appears because we pass the item_id parameter (which is the event parameter of Item ID dimension).

Firebase Analytics - Event Report

Full Code

  import 'package:firebase_analytics/firebase_analytics.dart';
  import 'package:firebase_analytics/observer.dart';
  import 'package:flutter/material.dart';
  
  void main() => runApp(MyApp());
  
  class MyApp extends StatelessWidget {
  
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        title: 'Woolha.com Flutter Tutorial',
        home: FirebaseAnalyticsExample(),
        debugShowCheckedModeBanner: false,
        navigatorObservers: [
          FirebaseAnalyticsObserver(analytics: FirebaseAnalytics()),
        ],
      );
    }
  }
  
  class FirebaseAnalyticsExample extends StatefulWidget {
  
    @override
    _FirebaseAnalyticsExampleState createState() => _FirebaseAnalyticsExampleState();
  }
  
  class _FirebaseAnalyticsExampleState extends State<FirebaseAnalyticsExample> {
  
    final FirebaseAnalytics _firebaseAnalytics = FirebaseAnalytics();
  
    @override
    void initState() {
      super.initState();
      _logAppOpen();
      _setAnalyticsProperties();
    }
  
    void _logAppOpen() async {
      await _firebaseAnalytics.logAppOpen();
    }
  
    void _setAnalyticsProperties() async {
      await _firebaseAnalytics.setUserId('000001');
      await _firebaseAnalytics.setUserProperty(
        name: 'favorite_color',
        value: 'pink',
      );
    }
  
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('Woolha.com Flutter Tutorial'),
        ),
        body: Center(
          child: OutlinedButton(
            child: const Text('Special Purchase'),
            onPressed: () async {
              await _firebaseAnalytics.logEvent(
                name: 'special_purchase',
                parameters: {
                  'special_purchase_amount': 100,
                  'item_id': 'item-001',
                },
              );
            },
          ),
        ),
      );
    }
  }

Summary

To use Firebase Analytics in a Flutter application, first you have to integrate the project with the Firebase account. In the Firebase Console, you probably need to define some new custom dimensions or metrics if you want to set custom user properties or log custom events. The firebase_analytics plugin makes it easier to track page transitions, set user properties, and log events. if everything goes well, you should be able to see the result in the Firebase Console.

You can also read about: