How to Add Firebase Analytics to Your Flutter App

Having firebase integrated to our Flutter applications has brought us many advantages. Firebase analytics get us more in-depth details of application details like active users, top conversation events, daily user engagement, crash free user percentage and more. Even for more, we can filter this all on the basis of Platform, Stream, Users custom data (like Gender, Age and etc.) & Signed in Status also. So, let’s start understanding how to integrate firebase analytics for a Flutter Application and get best use of generated analytics.

In this article, we’ll go over:

  • firebase analytics integration
  • gathering user properties
  • tracking of events

Firebase Analytics Integration

To integrate firebase analytics for our flutter project, follow steps provided here in their official details. Before integrating analytics, we have to integrate firebase core to our flutter project.

Firebase Core Integration

Firebase Analytics Integration

Once done we’re ready to move ahead with new steps. Now define a new class named FirebaseAnalyticsService and put below displayed code.

import 'package:firebase_analytics/firebase_analytics.dart'; 
import 'package:firebase_analytics/observer.dart'; 
 
class FirebaseAnalyticsService { 
  final FirebaseAnalytics _analytics = FirebaseAnalytics(); 
 
  FirebaseAnalyticsObserver appAnalyticsObserver() => 
      FirebaseAnalyticsObserver(analytics: _analytics); 
}

Now register this class in our servicelocator file:

 

serviceLocator.registerLazySingleton(() => FirebaseAnalyticsService());

 

From this point, our FirebaseAnalytcicsService class is ready to use for different usage of Firebase Analytics 

Screen View Tracking

In our FirebaseAnalyticsService class we have FirebaseAnalyticsObserver added which can be added to navigatorObservers to track screen view events. See the code below to do that.

navigatorObservers: [ 
  serviceLocator<FirebaseAnalyticsService>().appAnalyticsObserver(), 
],

After specifying class in navigatorObservers run the app and start moving around the different screens inside app. As of now we do have 3 screens where we can move around, Login, Register and Forgot Password. Once we do that, we can check reported events in section titled Realtime under Analytics portion on Firebase Console.

To get to this Realtime Events view, go to Realtime section and click on Events at bottom left corner. Now click on Top Event section on right of it and click on screen_view & choose firebase_previous_screen. Here we’ll get the details of screens which we have moved around on our device during app usage.

Track User Properties

Another benefit of having firebase analytics is we can track user properties like id, type of login, role & etc and get that information on analytics at Firebase console.

First, we’ll track user id and to simulate this flow we can put some delay before moving ahead with registering user id into analytics.

To do that we have to add a function accepting a string parameter called id & will registering that as user id on analytics. See code below.

Future setUserId({@required String? id}) async { 
  await _analytics.setUserId(id); 
}

 

Simulation can be done using below code snippet.

await Future.delayed(Duration(milliseconds: 3000)); 
await _analyticsService.setUserId(id: '101');

This is about user id but apart from this we can also track user defined properties like login type & role and to do that let’s accept another string parameters on same function and add that to analytics. See the updated code snippet below.

Updated Function

Future setUserProperties({ 
  @required String? id, 
  @required String? loginType, 
  @required String? userRole, 
}) async { 
  await _analytics.setUserId(id); 
  await _analytics.setUserProperty(name: 'login_type', value: loginType); 
  await _analytics.setUserProperty(name: 'user_role', value: userRole); 
}

Updated Function Call

await _analyticsService.setUserProperties( 
  id: '101', 
  loginType: 'EMAIL', 
  userRole: 'ADMIN', 
);

Get a free quote on your project!

Track Events

More with tracking user properties, firebase analytics also provide a way to track events from an application to be reported on Firebase console. Based on reported events and generated analysis future steps can be taken. Stating with common events like login and sign up which can be tracked using functions provided by analytics library itself as shown below.

Sign up Event

To report an event on user sign up, below method can be used.

Future logSignUp() async { 
  await _analytics.logSignUp(signUpMethod: 'email'); 
}

Along with the reporting event, we can also send what kind of sign-up procedure a user is preferring to take better decisions in for future functionalities.

Login Event

To report an event once a user login, below method can be used.

Future logLogin() async { 
  await _analytics.logLogin(loginMethod: 'email'); 
}

 

While reporting this event, additional details like method of login can also be sent to console to report what kind of login a user is preferring most of to take proper decision. 

As we can see in above image where Debug View has been started to check real time events triggered from device while moving around in our app. Refer here to learn how we can enable debug view for our apps. Once we do that and run our application, it will start reporting event to firebase & in debug view section we’ll get all details of ongoing session.

So, in above image we’re looking at an event titled login triggered with its details where, we mentioned a parameter method of login with value equals to email. It’s clearly visible & this is awesome, right. Now let’s talk about triggering custom events.

Custom Event

Previous events were default provided by firebase analytics library and there are bunch of other such functions we can use to report events to console. Additionally, we can also log custom event to firebase console for scenarios like where user has performed some purchase, on confirming order, payment gets success with payment gateway used, going ahead with levels in game and so on. Let’s see how a custom event can be logged on console.

Future logPurchaseDone( 
    {@required bool? paymentStatus, @required String? paymentGateway}) async { 
  await _analytics.logEvent( 
    name: 'purchase_done', 
    parameters: { 
      'payment_status': paymentStatus, 
      'payment_gateway': paymentGateway, 
    }, 
  ); 
}

Above method can be used to log event when a purchase has been made along with status of the payment and payment gateway has been used. Firebase analytics provide a function called logEvent which accepts name of the event and Map<String, String> containing other parameters we would like to send along with it.

In above image we can clearly see details of event titled purchase_done reported to firebase console from the application. Additionally, event’s parameters like payment_status and payment_gateway is also reported with their value we passed from application.

So, this is how we can have user properties and trigger events which are provided by default as well as custom to the firebase console. Now, let’s talk about benefits of getting all these information.

Benefits of Firebase Analytics for Your Flutter App

Talking about benefits of gathering such details from our application to firebase console, give us ability to filter out what users are doing and what they prefer to do more within our application. Based on this analysis we can promote as well as improve our marketing strategy to engage more user audience. Let’s see a small step before ending our talk.

Based on received information, we can create a new Audience with different conditions based on values we have received. So below what we have set for login_type equals to EMAIL and user_role equals to ADMIN and it will show us result that how many users (or Audience) are falling in selected categories.

So, this is how we can integrate Firebase analytics to our Flutter Project and get user properties and event tracked down to console and build up future roadmap based on analysis we have received. Try this for your ongoing flutter projects and see what kind of reports you all are able to generate.

Hope you have got some new details today & see you later in upcoming article with more interesting stuff but until then, happy coding!

To learn more about Flutter, check out our Tech Knowledge Base.

Published by
Janki Thaker

Recent Posts

  • Data & Analytics

7 Steps to Become Data Strategist & Drive Revenue Growth with Databricks

Without a strategy built by experts, your business could…

2 days ago
  • AI/ML

Your AI & Automation Strategy is the Outcome of 2 Key Steps

Strategically implementing AI & Automation can drive significant value,…

6 days ago
  • Data & Analytics

4 Important Things Decision-Makers Should Know About Data Analytics

Data-driven businesses are not only 23 times more likely…

1 week ago
  • Data & Analytics

7 Key Strategies for Building a Profitable Data Ecosystem with Databricks

Our key strategies for building a profitable data ecosystem…

1 week ago
  • AI/ML

Earning Potential of AI & Automation for Enhanced Productivity in 2025

Manufacturing alone is forecasted to experience a $3.78 trillion…

2 weeks ago