I need to access two different view model in one page in Flutter.
How to use nested Consumers in Flutter, Will they effect each other?
How can I use it in this code for example?
class CounterDisplay extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Consumer<CounterModel>(
builder: (context, counterModel, child) {
return Text('${counterModel.count}');
},
);
}
}
2
Answers
you can use
Consumer2<>
to access two different providers like this :With this, your
Text()
widget will be rebuilt each time one the providers value is changed withnotifyListener()
.If your
Text()
widget doesn’t need to be rebuilt with one of your providers, you can simply useProvider.of<MySecondProvider>(context, listen: false);
.Here for example:
I hope this helps!
You can absolutely nest consumers, but you need to understand if you really want them to nest.
Case 1: Nesting consumers:
Please note that if consumer for
CounterModel
is rebuilt, everything will be rebuilt. If consumer forSomeAnotherModel
is rebuild, only the part inside its builder would be rebuilt.Instead of using consumers this way, I’d recommend them to be used as in case 2 below.
Case 2: Use consumers on the required components: