Home > Net >  Should I inject Firebase instances?
Should I inject Firebase instances?

Time:11-28

I added firebase analytics to my project and I'm using analytics in every use case. So in every file, I need to create a firebase analytics instance. like FirebaseAnalytics analytics = FirebaseAnalytics.instance;.

So I was thinking what if I use getIt and inject the instance wherever I need in that case only one instance will be created. like getIt.registerSingleton(FirebaseAnalytics.instance);

What would be batter?

CodePudding user response:

There is no need to inject them using a dependency manager package, the Firebase services's instance getter is implemented like this:

   /// Returns an instance using the default [FirebaseApp].
  static FirebaseAuth get instance {
    FirebaseApp defaultAppInstance = Firebase.app();

    return FirebaseAuth.instanceFor(app: defaultAppInstance);
  }

  /// Returns an instance using a specified [FirebaseApp].
  /// Note that persistence can only be used on Web and is not supported on other platforms.
  factory FirebaseAuth.instanceFor(
      {required FirebaseApp app, Persistence? persistence}) {
    return _firebaseAuthInstances.putIfAbsent(app.name, () {
      return FirebaseAuth._(app: app, persistence: persistence);
    });
  }

so calling multiple instance getters across your entire app will not register it every time, it will register it only the first time with the putIfAbsent, after that it will directly return that instance.

CodePudding user response:

Instead of injecting the FirebaseAnalytics directly, use a Wrapper and inject that, like this.

Define your Wrapper first:

class Analytics {
  Analytics(this.firebaseAnalytics);

  final FirebaseAnalytics firebaseAnalytics;

  void logEvent(String eventName, Map<String, dynamic> params) {
    // log any analytics here.
  }
}

Create your wrapper.


final analytics = Analytics(FirebaseAnalytics.instance);

Inject your wrapper (you can use any service injector).


getIt.registerSingleton(analytics);

Then you can retrieve your dependency from any Widget/Bloc.

Why?

Imagine later you want to add or switch another Analytic provider, we'll just need to modify your wrapper instead of updating all of your widgets.

This will also help for testing, you will be able to mock your Wrapper.

  • Related