我们可以在Flutter Web应用程序中实施Firebase Analytics吗?如果没有,还有其他选择吗?
从firebase 7.0.0(https://pub.dev/packages/firebase/versions/7.0.0)开始,您可以在Flutter Web应用程序中使用分析。
步骤如下:
<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>
导入firebase包
import ‘package:firebase/firebase.dart’;
此时,您可以通过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); } } }
import 'dart:js' as js; ... Widget build(BuildContext context) { return MaterialApp( navigatorObservers: [AnalyticsRouteObserver(analytics: js.context.hasProperty('firebase')?analytics():null)], ... }