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);
2
Answers
There is no need to inject them using a dependency manager package, the Firebase services’s
instance
getter is implemented like this:so calling multiple
instance
getters across your entire app will not register it every time, it will register it only the first time with theputIfAbsent
, after that it will directly return that instance.Instead of injecting the
FirebaseAnalytics
directly, use a Wrapper and inject that, like this.Define your Wrapper first:
Create your wrapper.
Inject your wrapper (you can use any service injector).
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.