我希望通过Firebase分析在Flutter应用中跟踪选项卡更改。在示例应用程序中,它们只是将FirebaseAnalyticsObserver传递到小部件树下:
class MyApp extends StatelessWidget {
static FirebaseAnalytics analytics = FirebaseAnalytics();
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,
),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title, this.analytics, this.observer})
: super(key: key);
final String title;
final FirebaseAnalytics analytics;
final FirebaseAnalyticsObserver observer;
@override
_MyHomePageState createState() => _MyHomePageState(analytics, observer);
}
class _MyHomePageState extends State<MyHomePage> {
_MyHomePageState(this.analytics, this.observer);
final FirebaseAnalyticsObserver observer;
final FirebaseAnalytics analytics;
但是问题是我的标签页位于小部件树的下方。因此很难一路走下去。
如何初始化FirebaseAnalytics观察器以跟踪正常的屏幕路线,但也可以将其提供给标签页?
我正在使用Provider和ChangeNotifier。所以也许我可以初始化一个服务,然后提供下来?例如
class Analytic extends ChangeNotifier {
static FirebaseAnalyticsObserver observer =
FirebaseAnalyticsObserver(analytics: analytics);
}
答案 0 :(得分:0)
Flutter具有InheritedWidget,它是一个完全做到这一点的小部件,它一直向下传递数据,您可以检查official video showcase或某些articles。
要使用它,请使用继承的小部件包装小部件
class MyApp extends StatelessWidget {
final FirebaseAnalytics analytics = FirebaseAnalytics();//don't make this static please
final FirebaseAnalyticsObserver observer =
FirebaseAnalyticsObserver(analytics: analytics); //don't make this static please
@override
Widget build(BuildContext context) {
return ObserverProvider(
child: MaterialApp(
title: 'Firebase Analytics Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
navigatorObservers: <NavigatorObserver>[observer],
home: MyHomePage(
title: 'Firebase Analytics Demo'
),
),
observer:observer,
analytics:analytics
)
;
}
}
class ObserverProvider extends InheritedWidget {
const ObserverProvider(
{Widget child,
Key key,
this.observer,
this.analytics})
: super(key: key, child: child);
final FirebaseAnalytics analytics;
final FirebaseAnalyticsObserver observer;
static ObserverProvider of(BuildContext context) {
return (context.inheritFromWidgetOfExactType(ObserverProvider));
}
@override
bool updateShouldNotify(ObserverProvider e) => false;
}
如果要访问数据,则调用ObserverProvider.of(context).observer
代表观察者,并调用ObserverProvider.of(context).analytics
进行分析