When to use Provider.of<X> vs. Consumer<X> in Flutter

Oprimus picture Oprimus · Nov 8, 2019 · Viewed 18.5k times · Source

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:

  1. Is this the correct way to distinguish Provider.of<X> and Consumer<X>. Former doesn't update UI, latter does?
  2. If listen isn't set to false will the widget be rebuilt by default or not rebuilt? What if listen is set to true?
  3. Why have Provider.of with the option to rebuild the UI at all when we have Consumer?

Answer

R&#233;mi Rousselet picture Rémi Rousselet · Nov 9, 2019

It doesn't matter. But to explain things rapidly:

Provider.of is the only way to obtain and listen to an object. Consumer, Selector, and all the *ProxyProvider calls Provider.of to work.

Provider.of vs Consumer is a matter of personal preference. But there's a few arguments for both

Provider.of

  • can be called in all the widgets lifecycle, including click handlers and didChangeDependencies
  • doesn't increase the indentation

Consumer

  • allows more granular widgets rebuilds
  • solves most BuildContext misuse