一尘不染

Flutter Web:Flutter Web应用程序是否支持Firebase Analytics?

flutter

我们可以在Flutter Web应用程序中实施Firebase Analytics吗?如果没有,还有其他选择吗?


阅读 296

收藏
2020-08-13

共1个答案

一尘不染

从firebase
7.0.0(https://pub.dev/packages/firebase/versions/7.0.0)开始,您可以在Flutter
Web应用程序中使用分析。

步骤如下:

  1. 在您的主机页面中初始化Firebase
    <body>
      <!-- Initialize Firebase -->
      <script src="/__/firebase/7.6.1/firebase-app.js"></script>
      <script src="/__/firebase/7.6.1/firebase-analytics.js"></script>
      <script src="/__/firebase/init.js"></script>

      <!-- Initialize app -->
      <script src="main.dart.js" type="application/javascript"></script>
    </body>
  1. 导入firebase包

    import ‘package:firebase/firebase.dart’;

  2. 此时,您可以通过analytics()访问Analytics对象。如果您想自动发送页面浏览量,可以引入一个路线观察者

    class AnalyticsRouteObserver extends RouteObserver<PageRoute<dynamic>> {

      final Analytics analytics;

      AnalyticsRouteObserver({@required this.analytics});

      void _sendPageView(PageRoute<dynamic> route) {
        var pageName = route.settings.name;
        if (null != analytics) {
          analytics.setCurrentScreen(pageName);
        } else {
          print('pageName: $pageName');
        }
      }

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

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

      @override
      void didPop(Route<dynamic> route, Route<dynamic> previousRoute) {
        super.didPop(route, previousRoute);
        if (previousRoute is PageRoute && route is PageRoute) {
          _sendPageView(previousRoute);
        }
      }
    }
  1. 最后在您的应用中注册路线观察者
    import 'dart:js' as js;
    ...
    Widget build(BuildContext context) {
        return MaterialApp(
          navigatorObservers: [AnalyticsRouteObserver(analytics: js.context.hasProperty('firebase')?analytics():null)],
    ...
    }
2020-08-13