Firebase Analytics for Flutter without Named Routes

Firebase Analytics for Flutter is vary simple, how to create flutter application is well described in the documentation. And for more information about using Firebase, check out the docs on flutter development.

Lets create a simple Flutter application, this app have  3 pages: home, about, & contact. We’ll build a simple Drawer to use for navigation and we’ll discover how to navigate to a page based on a name. Before we begin let’s review how to navigate without a named route.


	Navigator.push(context, new MaterialPageRoute(builder: (context) => new AboutPage()));

Named routes makes it a bit easier. Here is how you might construct the same navigation to an about page using named routes:


	Navigator.of(context).pushNamed('/about');

Once your project is setup the code to track page views is as simple as


import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_analytics/observer.dart';
import 'package:flutter/material.dart';
import 'home.dart';
import 'about.dart';
import 'contact.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  
  FirebaseAnalytics analytics = FirebaseAnalytics();

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Firebase Analytics Demo',
      navigatorObservers: [
	FirebaseAnalyticsObserver(analytics: analytics),
      ],
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(),
      routes: <String, WidgetBuilder>{
        '/home': (BuildContext context) => new HomePage(),
        '/about': (BuildContext context) => new AboutPage(),
        '/contact': (BuildContext context) => new ContactPage(),
      },
    );
  }
}

If we using named routs then the 'Firebase Analytics' will track the name automatically. In the below code '/about' is the 'screen_view'


	Navigator.of(context).pushNamed('/about');

But the problem is if we are not using the named routs the 'screen_view' is always 'null'.

Then how to solve this 'screen_view' null issue for Flutter Firebase Analytics ?

The solution is also simple we can add RouteSettings in 'Navigator.push'


Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => HomePage(),
      settings: RouteSettings(name: '/home'),
    ),
  );
}

Navigator.of(context).push(
    MaterialPageRoute(
      builder: (context) => HomePage().
      settings: RouteSettings(name: '/home'),
    ),
  );
}

Thanks for reading, and hopefully this was helpful!