I have a question about Consumer, of Provider package, in Flutter. I don't understand the purpose of argument "child" in the builder of Consumer
Consumer<MyModel>(builder: (context, myModel, child) {
// doing stuff using myModel variable
});
I could not find any doc about it.
① The container widget has a property called child , which takes another widget. ② The Padding widget has a property called child also, which takes a widget. Other common properties in Flutter that allow you to pass widgets into widgets are children and builder .
The Consumer widget can also be used inside MultiProvider. To do so, it must return the child passed to builder in the widget tree it creates. MultiProvider( providers: [ Provider(create: (_) => Foo()), Consumer<Foo>( builder: (context, foo, child) => Provider. value(value: foo.
The answer is simple, and the power of the Provider package is in its simplicity: Providers allow to not only expose a value, but also create/listen/dispose it. When you place a Provider widget in your widget tree all the Childs of the Provider will have access to the values exposed by it.
ConsumerWidget class Null safetyA 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.
The child is any widget that doesn't need the data inside of the provider, so when the data gets updated, they don't get re-created since they don't need the data, rather they are passed as a reference to the builder.
Consumer(
builder: (context, myModel, child) {
// child will refer to the MaterialButton provided as the child argument in the
// Consumer named parameter,
// doing stuff using myModel variable
}
child: MaterialButton(
child: Text("Do some action"),
onPressed: () {
// do some actions
},),);
Since the MaterialButton doesn't need the state of the provider, but its in the descendant tree, there is no need to re-render that, so it gets passed back to the builder, to save memory and increase performance
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