2-Minute Read

253 words

After setting up Firebase and Google Analytics, Flutter can conveniently send screen_view events. However, this requires manually adding code to each page. I found a way to automate this process with minimal changes.

Using Mixin

The solution is to implement a Mixin and use it on each page.

import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';

// Define each screen here.
enum AnalyticsRoute {

mixin RouteAwareAnalytics<T extends StatefulWidget> on State<T>
    implements RouteAware {
  AnalyticsRoute get route;

  void didChangeDependencies() {
    routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);

  void dispose() {

  void didPop() {}

  void didPopNext() {
    // When the previous screen is popped, this screen will be shown.

  void didPush() {
    // When this screen is shown.

  void didPushNext() {}

  Future<void> _setCurrentScreen(AnalyticsRoute analyticsRoute) async {
    // Capitalize the first letter.
    String screenName =
        toBeginningOfSentenceCase(analyticsRoute.name.toString()) ?? '';
    await FirebaseAnalytics.instance.logEvent(
      name: 'screen_view',
      parameters: {
        'firebase_screen': screenName,
        // Assume the class name is screenName + "Screen", please use your own class name.
        'firebase_screen_class': '${screenName}Screen',

Use RouteAwareAnalytics in each screen:

class ExampleScreen extends StatefulWidget {
  _ExampleScreenState createState() => _ExampleScreenState();

class _ExampleScreenState extends State<ExampleScreen> with RouteAwareAnalytics {
  AnalyticsRoute get route => AnalyticsRoute.example;
  // Other code...

Remember to register routeObserver when initializing the app:

return MaterialApp(
  navigatorObservers: [
  // Other code...

The next day, you will see the data on the Google Analytics. If you want to debug in real-time, you can use DebugView.


  1. Stackoverflow answer
comments powered by Disqus

Recent Posts