Skip to content

Analytics

Tom Gilder edited this page May 9, 2021 · 1 revision

You can add support for logging pages to analytics via an RoutemasterObserver.

Here's an example with using Firebase Analytics:

final analytics = FirebaseAnalytics();
final observer = AnalyticsObserver(analytics: analytics);
final delegate = RoutemasterDelegate(
  observers: [AnalyticsObserver()],
  routesBuilder: (context) {
    // Routes
  }
);

class AnalyticsObserver extends RoutemasterObserver {
  final FirebaseAnalytics analytics;

  AnalyticsObserver({required this.analytics});

  @override
  void didChangeRoute(RouteData routeData, Page page) {
    analytics.setCurrentScreen(
      screenName: routeData.path,
    );
  }
}

Depending on your use case, there are several properties you might want to log:

  • routeData.fullPath is the full current route including query string, e.g. /product/1?query=string
  • routeData.path is the just the current path, without query string, e.g. /product/1
  • routeData.pathTemplate is the original template of the current path, e.g. /product/:id

Which one you choose depends on what you want to track: do you care how many users view any product page (pathTemplate), or which specific products they're viewing (path or fullPath)?

Another option is to use a custom page type:

class CustomPage extends MaterialPage {
  final String analyticsName;

  CustomPage({
    required this.analyticsName,
    required Widget child,
  }) : super(child: child);
}

final routeMap = RouteMap(routes: {
  '/': (_) => CustomPage(
        analyticsName: 'someCustomName',
        child: LoginPage(),
      ),
});

class AnalyticsObserver extends RoutemasterObserver {
  final FirebaseAnalytics analytics;

  AnalyticsObserver({required this.analytics});

  @override
  void didChangeRoute(RouteData routeData, Page page) {
    if (PageMetrics is CustomPage) {
      analytics.setCurrentScreen(screenName: page.analyticsName);
    }
  }
}
Clone this wiki locally