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 {
example,
}
mixin RouteAwareAnalytics<T extends StatefulWidget> on State<T>
implements RouteAware {
AnalyticsRoute get route;
@override
void didChangeDependencies() {
routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
super.didChangeDependencies();
}
@override
void dispose() {
routeObserver.unsubscribe(this);
super.dispose();
}
@override
void didPop() {}
@override
void didPopNext() {
// When the previous screen is popped, this screen will be shown.
_setCurrentScreen(route);
}
@override
void didPush() {
// When this screen is shown.
_setCurrentScreen(route);
}
@override
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 {
@override
_ExampleScreenState createState() => _ExampleScreenState();
}
class _ExampleScreenState extends State<ExampleScreen> with RouteAwareAnalytics {
@override
AnalyticsRoute get route => AnalyticsRoute.example;
// Other code...
}
Remember to register routeObserver
when initializing the app:
return MaterialApp(
navigatorObservers: [
routeObserver,
],
// 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.