Suppose you are working on a large app with a lot of folders and files. Now if the user has interacted with your app say pressed a button or something like that then the app has to build itself again to update to the changes that the user had made. So in this article, we will go through When to Use Provider.of<X> vs. Consumer<X> In Flutter.
When to Use Provider.of<X> vs. Consumer<X> In Flutter ??
What is Provider ??
A Provider is a container or storage that stores and provides you with state or data. Also, we know that widgets are arranged in an app like a tree-like fashion. So, if u assign the Provider to any node in the tree then all the children of that node will have access to the data that is provided by the Provider.
Back the stage, the Provider comes with a listener. Moreover, these listeners are assigned to the children of the widget to which the Provider is attached.
So, If the user interferes with a widget that has a listener then the app will build only that widget with which the user interacted again not the whole app.
However, Provider.of is the only way to obtain and listen to an object. Consumer, Selector and all the *ProxyProvider calls Provider.of to work. Provider.of vs Consumer is a matter of personal preference. But there are a few arguments for both.
- can be called in all the widgets lifecycle, including click handlers and didChangeDependencies.
- does not increase the indentation.
- allows more granular widget rebuilds.
- solves most BuildContext misuse.
Further for Your Information:
- Is this the correct way to distinguish Provider.of<X> and Consumer<X>? The former does not update UI, the latter does?
- Provider.of<X> depends on the value of listening to trigger a new State.build to widgets and State.didChangeDependencies for Stateful Widget.
- Consumer<X> always update UI, as it uses Provider.of<T>(context), where listen is true. See full source here.
- The default value is true, which means will trigger a new State. build to widgets and State.didChangeDependencies for Stateful Widget. See full source here.
- The widget Consumer does not do any fancy work. It just calls Provider.of in a new widget, and delegates its build implementation to the builder. It’s just syntactic sugar for Provider.of but the funny thing is Provider.of is simpler to use.
- Look at this article for more clearance https://blog.codemagic.io/flutter-tutorial-provider/.
Hope you like this article.
So today, we learned When to Use Provider.of<X> vs. Consumer<X> In Flutter.
Do not forget to share your valuable suggestions/feedback in the comments below.
Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget Guide, Flutter Projects, Code libs and etc.
Flutter Agency is one of the most popular online portals dedicated to Flutter Technology. Daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.