When to use Provider.of<X> vs. Consumer<X> in Flutter
Solution 1:
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
Solution 2:
For your questions:
- Is this the correct way to distinguish
Provider.of<X>
andConsumer<X>
. Former doesn't update UI, latter does?
Provider.of<X>
depends on value of listen
to trigger a new State.build
to widgets and State.didChangeDependencies
for StatefulWidget
.
Consumer<X>
always update UI, as it uses Provider.of<T>(context)
, where listen
is true
. See full source here.
- If
listen
isn't set tofalse
will the widget be rebuilt by default or not rebuilt? What iflisten
is set totrue
?
Default value is true
, means will trigger a new State.build
to widgets and State.didChangeDependencies
for StatefulWidget
. See full source here.
static T of<T>(BuildContext context, {bool listen = true})
.
- Why have
Provider.of
with the option to rebuild the UI at all when we haveConsumer
?
Pretty much covered by Rémi Rousselet's answer.
Solution 3:
Provider.of<>
applying provider, whole widget will rebuild if listen true.
Consumer<>
using consumer only specifically allowed widget will rebuild.