1

我想使用 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);
}
4

1 回答 1

0

Flutter 有 InheritedWidget,一个正是这样做的小部件,它一路向下传递数据,你可以查看官方视频展示,或一些文章

要使用它,您可以使用继承的小部件包装小部件

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分析

于 2019-11-04T17:45:48.460 回答