Provider vs. Get_it - flutter

Searching for Dependency Injection solutions for Flutter, I found two awesome libraries: provider and get_it.
As far as I can see, provider has more boilerplate, but it fits really nicely with Flutter, allowing Consumer to rebuild parts of the Widget tree, once an injected value change.
get_it on the other hand is more straightforward, easier to use, and not dependant on Flutter, so can be used with any Dart code.
Are there any more differences and limitations between them? I know this is kinda opinionated, but Flutter is so new that it's good to register publicly benefits, side-effects and gotchas.

The main difference between both is that provider is not strictly dependency injection.
By using widgets, provider is also able to:
providers are compatible with the Flutter devtool
know when a variable cannot be accessed (scoped to a tree)
know when to create and dispose of an object
synchronize model -> model and model -> UI
override some values for only a specific widget tree
voluntarily prevent circular dependency
All of these are, while optional, good for the health of your app in the long run.
It ensures that you're always up to date, makes it harder to have "spaghetti code", and makes your different elements more composable.

I am explaining just one limitation which I practically found, there may be others too.
After searching many tutorials and topics on Get_it that why people use Get_it() even we have dependency injection in the provider, I was unable to understand the difference in terms of DI. Then I stuck in a Scenario and find the answer to your question that "what are the limitations".
Are there any more differences and limitations between them?.
Scenario:
I had Nested widgets, Widget A has Widget B and Widget B has Widget C, I was using the provider and was accessing values in each widget whenever value changed. It was great, Then I make a new widget D which was a separate widget, it was not inside the widget A hierarchy. But when I try to access the same value in Widget D it was not changing. Because widget D is not in the tree of Widget A. Now here comes the limitation of dependency injection of the provider.
Conclusion
You will use Get_it to access values out of the tree widget. But you can't access the
updated value using provider
Updated Answer
In the above scenario, you need to wrap the app with Provider to access all dependencies.

Get It is not a dependency injection solution but a service locator.
It's useful if you want to rapidly switch between two or more implementations of a class. For example to mockup a service, and change between the "real" service or the fake one (for debugging purpose).
Indeed it can't retrieve/supply reference to an existing object (exception is for singleton, but you can do the same by yourself without much more effort) and can supply only new objects.

from streaming through various tutorials what I learned is that the get it package can be called a global variable that can be accessed from any widget to any widget whether nested or not nested VS provider which can only be accessed between the nested widget.
The example is better explained by
M.ArslanKhan

Related

Why you should use Riverpod?

There is setState and moreover Provider, using which you can manage your states easily and neatly, then why Riverpod?,
I see different examples in enter link description here where riverpod is being used, I just find each example making simple things more complicated, when you use Riverpod, same things can be done more easily with Provider or just using setState and following some good techniques while managing states in codes.
there is a package named hooks_riverpod, I don't find the justification of this package just to support riverpod you hacked all the statndard widgets although there is another version flutter_riverpod but using hooks is not an intended approach maybe helpful for people coming from reactjs background but flutter engineers have not designed flutter this way, using these non-standard approaches you are just trapping yourself within the mercy of these few packages.
Inherited widgets is only standard approach given by flutter of managing states across the app, Provider and some other Packages like Redux they just follow the same approach.
If you may have used the Riverpod or related packages please share your experience.
It depends on the project and how you like to handle state. If you are ok with setState management/Inherited widgets, you don't need to use others.
I like share some reference here, On riverpod doc second section you can find
Provider, without its limitations
Riverpod is inspired by Provider but solves some of it's key issues such as supporting multiple providers of the same type; awaiting asynchronous providers; adding providers from anywhere, ...
riverpod, Dart only (NO flutter)
flutter_riverpod, A basic way of using Riverpod with flutter. You mostly use it for state management.
If you are using hook widgets(flutter_hooks) that reduce the boilerplate code like dispose, you can use hooks_riverpod
Also, all these packages provided by same author Remi Rousselet
Well, there's a lot of debate on a good state management solution out there.
But in your context, I'd like to mention some points.
Why Riverpod over Provider?
Well, Riverpod was built to fix some issues of Provider which would have been impossible to fix in Provider.
Like:
Majorly, Riverpod is compile safe.
Solves stuff like multiple providers, adding providers from anywhere.
Removes Flutter dependence, there's no need of using contexts anymore like that were used in Provider.
and others... for more on that you can refer to the home page of Riverpod here
Also, Remi, the creator of Riverpod & Provider suggests using Riverpod over Provider.
Secondly, why not setState?
Well, you can't build a featured application just using setState with proper programming standards. You would have to pass up and down data in your application continuously with Prop Drilling. Imagine having 5 widgets under a parent widget and the parent widget needs the data in the 5th sub widget. This is just a normal case, it could go much worse in actual applications.
About hooks?
Well, yes, it's well easy for React devs to quickly jump on to Flutter. But that's just not the case it was developed for. Its main purpose is to use reusable functional widgets. So, a good example of this will always be, when you're using Animation Controller and you've to maintain its lifecycle every time you use it. I can't go in depth here, for that you can refer to the docs.

Flutter(Cubit and Repository) - Where to inject dependencies

I'm relatively new to Flutter and Cubit pattern and I'm trying to figure out which are the best ways to work with them. Recently my colleague and I have been struggling to reach an agreement where we should inject the cubit and the repositories.
Reading the bloc/cubit documentation, it is not very clear about where we should do it.
IMO, everything that we need to instantiate, should be injected as high in the tree as possible where two different components that will use this information have in common.
For my colleague, each widget can instantiate one cubit, meaning that each widget will have its own instance of the cubit.
I would like to discuss about what are the community thoughts and best practices regarding the dependency injection and architecture regarding cubit.
There is no single answer to that question. It all depends on your project structure and architecture. In general though:
It's OK to create a few cubits/blocs in one screen/widget. Some widgets or screens contain more than one business logic stuff. Cubits are just classes that help you maintain the state, but it's no different than having many animation controllers or text editing controllers, it's just that it serves a more high-level state management. Let's say that you have a comments section in your app. You may have:
a cubit for the comments themselves, to load them, load more on scroll, report error when loading failed etc.
a cubit for each comment that manages the "Like" button under a comment
It's perfectly valid to have it that way.
It's OK to have global cubits for the whole app. There are some things that you need to have access to from the whole application. It usually is navigation (Navigator), and some theme management (Theme), why not something more business-logic related then, like authentication logic, current user context, user's app preferences, etc.? :)
IMO, everything that we need to instantiate, should be injected as high in the tree as possible where two different components that will use this information have in common.
This is a good approach. Most frequently it will be above your routes, so somewhere above your MaterialApp. If you make use of nested Navigators, then this common place could be above this nested Navigator.
On a more technical side, how will you manage the dependencies used in those cubits/blocs is up to you and your liking. I find some of the options:
Instantiating all repositories and other dependencies in main.dart method and then passing them in constructors to your blocs/cubits in Providers.
To reload those dependencies you will need a Hot Restart though, Hot Reload won't be enough.
Putting your dependencies in the widget's tree with Provider, just like blocs/cubits.
Using riverpod instead of provider.
Using a Service Locator pattern with get_it and injectable combo.
The most correct choice will be something that you (and your colleagues) are most comfortable developing with and that scales well.

Is it a best practise to pass provider as an argument to widgets?

Is it a best practise to pass provider as an argument to widgets?
I am aware that we can directly access provider from within the widget.
But saw a couple of code snippets passing provider as an argument to child widget.
Does it optimize the code? Or any possible leaks?
It is better to access the provider from within the widget that requires it, since the Provider uses the BuildContext (as in Provider.of(context)) to fetch an instance of the requested provided service, based on the location of the widget in the widget tree as it traverses the hierarchy above to find it. You can do it for convenience, but widgets should be encapsulated enough and decoupled enough so as not to depend on higher above widgets to get data fed to them, making them self-sufficient and independent. My two cents.

Example of why state management approach that doesn’t need a BuildContext is bad

There are so many Flutter state management approaches https://flutter.dev/docs/development/data-and-backend/state-mgmt/options
To avoid opinionated response, can someone provide a concrete example that supports why state management approach that doesn’t need a BuildContext is "bad" or "red flags"
One argument to use a state management package without BuildContext is this:
The fact that you need a BuildContext to access your objects made it
inaccessible from the Business layer.
Technically, there is no state management that does not need a BuildContext.
A widget does not exist by itself in Flutter. A Widget is accompanied by an Element. The Element maintains the position of the widget in the widget tree. If the element is mounted, then the widget is present in the widget tree. When the element is unmounted, it gets removed from the widget tree permanently. The Element contains functions like update, rebuild, performRebuild, updateChildren and many other functions that are used by the framework to manage the lifetime and under-the-hood behaviour of widgets, for updating state and for many other functionalities. You always need this Element to update the state of the corresponding Widget. Both StatelessWidget and StatefulWidget uses this element to re-render.
Surprise, surprise, the Element is actually an implementation of BuildContext as seen in framework.dart
I know that you meant using BuildContext to retrieve the object representing the state. This is more of a design choice than a technical requirement that package authors have to make. Essentially, you are using context to get the state object instance that were associated to the corresponding widget tree branch, by some parent widget. That's it. And you are doing that instead of the otherwise approach of passing around the class instance that represents state to children widgets. Both are "ok" approaches to state management.
Limiting to using the context alone is honestly in my opinion, a poor design decision. I personally believe that using context everytime to be able to incorporate state management, is just tideous. In many cases I have seen countless of apps that instantiate the Controller or ChangeNotifier only once and inject it to the root-level widget. Essentially using only one instance. One major purpose of using BuildContext is that you can provide multiple instances to multiple array of children and thereby differentiate their behaviour. But the reality is that a vast majority of apps DO NOT NEED this functionality. Another bonus of using Context is that you can retrieve object instances (of Controllers, ChangeNotifiers...) dynamically like Provider.of<MyClass>(context), without passing them around all the time. Essentially this is an example of dependency injection. But this is more of a poor design decision than great technical feat, as the source of your class instance is ambiguous. You only know the type of the instance. But ultimately, everything is personal preference, and if you are working, is often up to people who manage you to decide what architecture and state management solution to use. There are apps written using all of these "correct" approaches to state management.
You can checkout Turbo by the way. It is a very simple & efficient approach to state management I created, that does not use contexts to maintain and update state, at least not yet. It also has one of the easiest event systems so as to subscribe your widgets to only specific events.

Using Flutter Provider means no StatefulWidgets?

I'm getting ready to write my first nontrivial app with Flutter and Provider. I've read up on how Provider facilitates immutable widgets (StatelessWidgets). My question is, is it always an antipattern to use StatefulWidgets when using Provider? If not, what are examples of when it better to use StatefulWidgets in a Provider app?
EDIT
It's been a couple months using Provider and I'm still favoring it over StatefulWidgets in every case. Every now and again I introduce a StatefulWidget, mostly to try to gain familiarity with them, and almost immediately regret it and refactor to Provider. The other day I ran into widgets not refreshing because they were identical types, so was looking at introducing keys so they would refresh. First couple attempts failed, so I refactored into Provider and everything just worked (without the need for keys).
Antipattern was not the proper term in my OP. I guess my question is, are there examples where StatefulWidgets are cleaner or otherwise easier/better to use?
provider doesn't care whether you write stateless/stateful or anything else (hooks?).
It removes the need to write a StatefulWidget in many situations, but it doesn't claim that you should use StatelessWidget only.
In the end, it's your job to decide if you need a StatefulWidget or not. You may need it when writing animations for example.
Adding to Rémi's answer and new to this implementation:
use Provider for shared models
use widget state to manage the model that is specific to that concern when it's needed
imagine a user object after auth, null before, shared through an app, with a form with state specific to editing fields, like a nickname, or whatever, updating local state and possibly propagating out to the rest of the product (when finished updating on the backend?...who knows) and that state is disposed of when that view isn't needed anymore, but the user reference remains via the provider reference. It doesn't make sense to manage all that state change in the provider model--that's where the result goes.
Making a few assumptions here based on my experience with React+Redux as well as passing objects around a native Web Components (similar lifecycle to both of these) as well as LitElement. The patterns seem similar if not the same so-far.
Provider.of<ProviderClass>(context, listen: false);
The Provider is one of state management mechanism which Flutter has, under the hood, Provider keeps track of the changes which are done inside the widget. It doesn't matter to Provider whether it's a Stateless widget or Stateful widget, It's gonna rebuild widget if anything gets change.
listen: false tells the Provider not to rebuild widget even if data gets modified. That means it can only re-build if the parent widget gets modified by setState() or by the ProviderClass class value gets modified.