问题描述
我仍然对 Flutter 中的状态管理技术感到困惑,并且对何时以及为何使用 Provider.of
与 Consumer 感到有些困惑..我从文档中了解到(我认为)当在这两者之间进行选择时,您将使用 Provider.of 当我们想要访问数据时,但您不需要更改 UI.因此,以下(取自文档)可以访问数据并在新事件上更新 UI:
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}');
},
),
),
);
然而,如果我们只需要关于不想使用 UI 重建的数据,我们将使用带有
listen
参数集的 Provider.of
改为 false
,如下:
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
但是,
listen
不是必需的,因此以下内容也会运行:
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:
这是区分
Provider.of
和Consumer
的正确方法吗?前者不更新 UI,后者更新?如果
listen
没有设置为false
,widget 会默认重建还是不重建?如果listen
设置为true
会怎样?当我们有
Consumer
时,为什么Provider.of
可以选择重建 UI?
Is this the correct way to distinguish
Provider.of<X>
andConsumer<X>
. Former doesn't update UI, latter does?If
listen
isn't set tofalse
will the widget be rebuilt by default or not rebuilt? What iflisten
is set totrue
?Why have
Provider.of
with the option to rebuild the UI at all when we haveConsumer
?
推荐答案
没关系.但要快速解释一下:
It doesn't matter. But to explain things rapidly:
Provider.of
是获取和监听对象的唯一方式.Consumer
、Selector
和所有 *ProxyProvider 调用 Provider.of
工作.
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
与 Consumer
是个人喜好的问题.但两者都有一些论据
Provider.of
vs Consumer
is a matter of personal preference. But there's a few arguments for both
可以在所有小部件生命周期中调用,包括点击处理程序和
didChangeDependencies
不会增加缩进
允许更精细的小部件重建
解决大部分 BuildContext 误用问题
这篇关于何时使用 Provider.of<X>与消费者 X 对比在颤振中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!