Flutter Provider: notifyListeners() to specific target Flutter Provider: notifyListeners() to specific target dart dart

Flutter Provider: notifyListeners() to specific target


First, note that the optimization that you're trying to do is, most of the time, pointless.

Optimizing rebuilds has usually very little benefits, and may not be worth the added complexity and is useful only when the states change at a very frequent rate (like animations).

That said, what you're looking for is Selector.

Selector is a custom may of consuming providers which, as opposed to Consumer/Provider.of, has a way to filter undesired updates.

For example, if a widget only needs MyModel.text, then instead of:

final model = Provider.of<MyModel>(context);return Text(model.text);

we can use Selector like so:

return Selector<MyModel, String>(  selector: (_, model) => model.text,  builder: (_, text, __) {    return Text(text);  });

Such code will call builder again only when MyModel.text changes, and ignores changes to anything else.


You can see the code above

...return FlatButton(  child: Text(Provider.of<mybuttons>(context).getText(buttons)),  onTap: (){   Provider.of<mybuttons>(context).changeIndex(buttonIndex);  });

And mybuttons notifier must have a data structure that store the states of buttons and must have getText and changeIndex methods.

I am just wondering why don't you just simple a stateful widget?