Home > Software design >  How to make the provider rebuilding only certain widget?
How to make the provider rebuilding only certain widget?

Time:02-23

I am a newbie in in provider and i have 2 question regarding of rebuild tree

i have this class

class Myprovider extends ChangeNotifier {
  bool isFound= false;

  bool get isFoundM=> isFound;

  void changeStatus(bool status){
    isFound= status;
    notifyListeners();
  }
}

and i have stflwidget which contains the following code under build method

 Myprovider myProvider = Myprovider ();
    Column(
        mainAxisAlignment: myProvider.isFound?  MainAxisAlignment.center: MainAxisAlignment.start,
        children:[

          myProvider.isFound? const Text('Hello flutter'):Container(),

          const Text('Hello dart'),

          TextButton(
              onPressed:(){
                myProvider.changeStatus(true);
              },

              child: Text('tab me')
          )

        ]
    );

1- when i tab the Button , is Hello flutter Text only will only rebuilt its self or the whole tree will be rebuild ?

2- what about the widgets property in my column above ? .. it will only rebuilt the property even if it's parent was wrapping several widgets ?

if no How can i handle this

thanks

CodePudding user response:

Stateful widget has nothing to do with provider.

Stateful Widget are only useful when you are working with SetState. Where every widget under build context get updated and it will not help you to update any certain widgets

Building certain widgets with provider

When working with provider you can build certain widgets with out rebuilding the whole content

For that you can use Consumer

Foo(
  child: Consumer<A>(
    builder: (_, a, child) {
      return Bar(a: a, child: child);
    },
    child: Baz(),
  ),
)

NB:-In this example, only Bar will rebuild when A updates. Foo and Baz won't unnecessarily rebuild.

  • Related