I'm still wrapping my head around state-management techniques in flutter and am a bit confused about when and why to use Provider.of<X>
vs. Consumer<X>
. I understand (I think) from the documentation that when choosing between these two you would use Provider.of when we want access to the data, but you don't need the UI to change. So the following (taken from the docs) gets access to the data and updates the UI on new events:
return HumongousWidget(
// ...
child: AnotherMonstrousWidget(// <- This widget will rebuild on new data events
// ...
child: Consumer<CartModel>(
builder: (context, cart, child) {
return Text('Total price: ${cart.totalPrice}');
},
),
),
);
Whereas, where we only need the data on don't want to rebuild with UI, we'd use Provider.of<X>
with the listen
parameter set to false
, as below:
Provider.of<CartModel>(context, listen: false).add(item); \Widget won't rebuild
However, listen
isn't required and so the following will run too:
Provider.of<CartModel>(context).add(item); \listener optional
So this brings me to a few questions:
- Is this the correct way to distinguish
Provider.of<X>
and Consumer<X>
. Former doesn't update UI, latter does?
- If
listen
isn't set to false
will the widget be rebuilt by default or not rebuilt? What if listen
is set to true
?
- Why have
Provider.of
with the option to rebuild the UI at all when we have Consumer
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…