Ad

FirebaseAnalytics LogEvent By Creating A New Instance Each Time In Flutter

I'm adding Google Analytics to my Flutter project. Is it OK to log events in a static function like this?

static Future<void> logEvent(String eventName) async {
  await FirebaseAnalytics().logEvent(name: eventName);
}

FirebaseAnalytics is initialized each time the function is called. Will this cause problems?

Ad

Answer

It will not cause any problems except a small overhead, but it's nice to have it as a singleton. Eg., later you might realize that it makes sense to wrap the analytics reporting with some custom logic and you don't want to copy it around. InheritedWidget helps to get the same object instance from anywhere down the tree.

class Analytics extends InheritedWidget {
 final FirebaseAnalytics _analytics;

  Analytics(this._analytics, Widget child) : super(child: child);

  @override
  bool updateShouldNotify(Analytics oldWidget) {
    return _analytics != oldWidget._analytics;
  }

  static FirebaseAnalytics of(BuildContext context) {
    final provider =
        (context.getElementForInheritedWidgetOfExactType<Analytics>()?.widget) as Analytics;

    assert(provider != null);

    return provider._analytics;
  }
}

Put it on op of the widget tree when you build your app:

@override
Widget build(BuildContext context) {
    FirebaseAnalytics analytics = FirebaseAnalytics();
    var firebaseAnalyticsObserver = FirebaseAnalyticsObserver(
      analytics: analytics,
    );
    return Analytics(
      analytics,
      MaterialApp(
        navigatorObservers: [
          firebaseAnalyticsObserver,
        ],
        ...

Access it from any widget that's lower down the tree:

Analytics.of(context).logEvent(name: "my_custom_event");
Ad
source: stackoverflow.com
Ad