使用 Navigator 2.0 的 Flutter Firebase 分析跟踪应用程序屏幕变化

Flutter Firebase analytics tracking app screen change with Navigator 2.0

我发现的所有示例都使用 MaterialApp 构造函数中的“navigatorObservers”

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Firebase Analytics Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      navigatorObservers: <NavigatorObserver>[observer],
      home: MyHomePage(
        title: 'Firebase Analytics Demo',
        analytics: analytics,
        observer: observer,
      ),
    );
  }

但我的应用程序使用 Navigator 2.0 模式中的 MatterialApp.router,无法找到用于附加 navigatorObserver 的等效项,以便为 firebase 分析跟踪屏幕更改事件。对此有任何解决方法或建议吗?

MaterialApp.router constructor has required routerDelegate property. This delegate is usually a wrapper of the Navigator widget. This widget has observers 属性 - 这正是您要找的。

这里是 RouterDelegate 的一个例子,它注册了 Firebase 和 Segment 观察者:

class AppNavigator extends RouterDelegate<void>
    with ChangeNotifier, PopNavigatorRouterDelegateMixin<void> {
  AppNavigator({
    @required Page<void> initialPage,
    this.analyticsObserver,
    this.segmentObserver
  })  : assert(initialPage != null),
        navigatorKey = GlobalKey<NavigatorState>() {
    _pagesStack = [initialPage];
  }

  final FirebaseAnalyticsObserver analyticsObserver;
  final SegmentObserver segmentObserver;

  ...

  @override
  Widget build(BuildContext context) {
    return Navigator(
      key: navigatorKey,
      pages: [..._pagesStack],
      observers: [analyticsObserver, segmentObserver],
      onPopPage: (route, dynamic result) {
        if (!route.didPop(result)) {
          return false;
        }

        for (final page in _pagesStack) {
          if (page == route.settings) {
            _pagesStack.remove(page);
            notifyListeners();
            break;
          }
        }

        return true;
      },
    );
  }
}

请注意,在默认情况下,Firebase Analytics 模块希望您的页面路由将 name 属性 设置为 RouteSettings 的一部分:

  // From FirebaseAnalyticsObserver
  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,
      );
    }
  }

您可以通过向 FirebaseAnalyticsObserver 构造函数提供自定义 nameExtractor 属性 来覆盖此行为。