Skip to content

Commit

Permalink
fix(analytics): reinstate Analytics screen navigation observer. (#7529)
Browse files Browse the repository at this point in the history
  • Loading branch information
russellwheatley committed Dec 10, 2021
1 parent c657ade commit caf2986
Show file tree
Hide file tree
Showing 4 changed files with 128 additions and 3 deletions.
Expand Up @@ -31,6 +31,8 @@ class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

static FirebaseAnalytics analytics = FirebaseAnalytics.instance;
static FirebaseAnalyticsObserver observer =
FirebaseAnalyticsObserver(analytics: analytics);

@override
Widget build(BuildContext context) {
Expand All @@ -39,9 +41,11 @@ class MyApp extends StatelessWidget {
theme: ThemeData(
primarySwatch: Colors.blue,
),
navigatorObservers: <NavigatorObserver>[observer],
home: MyHomePage(
title: 'Firebase Analytics Demo',
analytics: analytics,
observer: observer,
),
);
}
Expand All @@ -52,10 +56,12 @@ class MyHomePage extends StatefulWidget {
Key? key,
required this.title,
required this.analytics,
required this.observer,
}) : super(key: key);

final String title;
final FirebaseAnalytics analytics;
final FirebaseAnalyticsObserver observer;

@override
_MyHomePageState createState() => _MyHomePageState();
Expand Down Expand Up @@ -319,7 +325,7 @@ class _MyHomePageState extends State<MyHomePage> {
MaterialPageRoute<TabsPage>(
settings: const RouteSettings(name: TabsPage.routeName),
builder: (BuildContext context) {
return const TabsPage();
return TabsPage(widget.observer);
},
),
);
Expand Down
Expand Up @@ -6,7 +6,9 @@ import 'package:flutter/material.dart';
import 'package:firebase_analytics/firebase_analytics.dart';

class TabsPage extends StatefulWidget {
const TabsPage({Key? key}) : super(key: key);
TabsPage(this.observer, {Key? key}) : super(key: key);

final FirebaseAnalyticsObserver observer;

static const String routeName = '/tab';

Expand Down Expand Up @@ -36,10 +38,12 @@ class _TabsPageState extends State<TabsPage>
@override
void didChangeDependencies() {
super.didChangeDependencies();
widget.observer.subscribe(this, ModalRoute.of(context)! as PageRoute);
}

@override
void dispose() {
widget.observer.unsubscribe(this);
super.dispose();
}

Expand Down
Expand Up @@ -4,15 +4,17 @@

library firebase_analytics;

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'
show FirebasePluginPlatform;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:firebase_analytics_platform_interface/firebase_analytics_platform_interface.dart';
export 'package:firebase_analytics_platform_interface/firebase_analytics_platform_interface.dart'
show AnalyticsEventItem, AnalyticsCallOptions;
import 'package:flutter/widgets.dart';

part 'src/firebase_analytics.dart';
part 'src/observer.dart';
113 changes: 113 additions & 0 deletions packages/firebase_analytics/firebase_analytics/lib/src/observer.dart
@@ -0,0 +1,113 @@
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

part of firebase_analytics;

/// Signature for a function that extracts a screen name from [RouteSettings].
///
/// Usually, the route name is not a plain string, and it may contains some
/// unique ids that makes it difficult to aggregate over them in Firebase
/// Analytics.
typedef ScreenNameExtractor = String? Function(RouteSettings settings);

String? defaultNameExtractor(RouteSettings settings) => settings.name;

/// A [NavigatorObserver] that sends events to Firebase Analytics when the
/// currently active [PageRoute] changes.
///
/// When a route is pushed or popped, [nameExtractor] is used to extract a name
/// from [RouteSettings] of the now active route and that name is sent to
/// Firebase.
///
/// The following operations will result in sending a screen view event:
/// ```dart
/// Navigator.pushNamed(context, '/contact/123');
///
/// Navigator.push<void>(context, MaterialPageRoute(
/// settings: RouteSettings(name: '/contact/123'),
/// builder: (_) => ContactDetail(123)));
///
/// Navigator.pushReplacement<void>(context, MaterialPageRoute(
/// settings: RouteSettings(name: '/contact/123'),
/// builder: (_) => ContactDetail(123)));
///
/// Navigator.pop(context);
/// ```
///
/// To use it, add it to the `navigatorObservers` of your [Navigator], e.g. if
/// you're using a [MaterialApp]:
/// ```dart
/// MaterialApp(
/// home: MyAppHome(),
/// navigatorObservers: [
/// FirebaseAnalyticsObserver(analytics: service.analytics),
/// ],
/// );
/// ```
///
/// You can also track screen views within your [PageRoute] by implementing
/// [PageRouteAware] and subscribing it to [FirebaseAnalyticsObserver]. See the
/// [PageRouteObserver] docs for an example.
class FirebaseAnalyticsObserver extends RouteObserver<PageRoute<dynamic>> {
/// Creates a [NavigatorObserver] that sends events to [FirebaseAnalytics].
///
/// When a route is pushed or popped, [nameExtractor] is used to extract a
/// name from [RouteSettings] of the now active route and that name is sent to
/// Firebase. Defaults to `defaultNameExtractor`.
///
/// If a [PlatformException] is thrown while the observer attempts to send the
/// active route to [analytics], `onError` will be called with the
/// exception. If `onError` is omitted, the exception will be printed using
/// `debugPrint()`.
FirebaseAnalyticsObserver({
required this.analytics,
this.nameExtractor = defaultNameExtractor,
Function(PlatformException error)? onError,
}) : _onError = onError;

final FirebaseAnalytics analytics;
final ScreenNameExtractor nameExtractor;
final void Function(PlatformException error)? _onError;

void _sendScreenView(PageRoute<dynamic> route) {
final String? screenName = nameExtractor(route.settings);
if (screenName != null) {
analytics.setCurrentScreen(screenName: screenName).catchError(
(Object error) {
final _onError = this._onError;
if (_onError == null) {
debugPrint('$FirebaseAnalyticsObserver: $error');
} else {
_onError(error as PlatformException);
}
},
test: (Object error) => error is PlatformException,
);
}
}

@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPush(route, previousRoute);
if (route is PageRoute) {
_sendScreenView(route);
}
}

@override
void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
if (newRoute is PageRoute) {
_sendScreenView(newRoute);
}
}

@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPop(route, previousRoute);
if (previousRoute is PageRoute && route is PageRoute) {
_sendScreenView(previousRoute);
}
}
}

0 comments on commit caf2986

Please sign in to comment.