I can't wrap my head around using multiple consumers for a single widget with provider? Suppose my widget is CurvedNavigationBar and I have 4 items in that widget. I also have 4 different classes that extend ChangeNotifier and are responsible for each item in CurvedNavigationBar.
How can I listen to those 4 change notifiers in a single widget? I looked at the documentation and could not found such an example.. is this even possible? I found that Consumer has a builder method, so that means you can build a widget only once/and listen to it once.
Should I rather have a single class that extends ChangeNotifier and then update values in that widget and uses only a single Consumer to listen for updated values?
A StatelessWidget that can listen to providers. Using ConsumerWidget, this allows the widget tree to listen to changes on provider, so that the UI automatically updates when needed. Do not modify any state or start any http request inside build.
One of the main reasons to prefer Provider over Statefulwidget s is that, using Provider , you will rebuild only the widgets that needs that value (the Consumers ) while the other will not be rebuilt. Instead when you call setState the whole build function of the widget will be called.
The generics (values inside <> brackets) tell Flutter what type of provider to look for. Then Flutter goes up through the widget tree until it finds the provided value. If the value isn’t provided anywhere then an exception is thrown. Finally, once you’ve got the provider, you can call any method on it.
But the provider pattern is far easier to learn and has much less boilerplate code. In this post, we’ll take the default Counter app provided by Flutter and refactor it to use the provider pattern. If you want to know what the Flutter team at Google has to say about the provider pattern, check out this 2019 talk.
With this done, we can now use the provider pattern in Flutter to set and get the counter value. On each button click we need to increment the counter value by 1. So, in the _incrementCounter method (which is called when the button is pressed) add this line:
Practically, that means that the consumer uses the builder pattern that's common with widgets. Using this pattern, the Consumer widget exposes some nice objects that make working with the provided models easier. Here's the example above again, but using a Consumer:
There are some other Consumer
widgets. Consumer2
, Consumer3
, Consumer4
till Consumer6
. If you want to listen 4 ChangeNotifier you can use Consumer4
Consumer4( builder: (context, changeNotifier1, changeNotifier2, changeNotifier3, changeNotifier4, child) { // your widget } )
Yes you can add up to 6 consumers and will be as following
Consumer2<AuthProvider, StorageProvider>( builder: (context, authProvider, storageProvider, child) { } )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With