Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of child in Consumer Provider Flutter

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.

like image 346
Dimitri Leurs Avatar asked Feb 18 '20 20:02

Dimitri Leurs


People also ask

What is a child in Flutter?

① 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 .

How do you use Consumer in provider in Flutter?

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.

Why do we use provider in Flutter?

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.

What is ConsumerWidget?

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.


1 Answers

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

like image 90
Ahmed Khattab Avatar answered Oct 07 '22 05:10

Ahmed Khattab