何时使用 Provider.of<X>与消费者 X 对比在颤振中 [英] When to use Provider.of<X> vs. Consumer<X> in Flutter

查看:29
本文介绍了何时使用 Provider.of<X>与消费者 X 对比在颤振中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然对 Flutter 中的状态管理技术感到困惑,并且对何时以及为何使用 Provider.ofConsumer 感到有些困惑..我从文档中了解到(我认为)当在这两者之间进行选择时,您将使用 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:

  1. 这是区分Provider.ofConsumer的正确方法吗?前者不更新 UI,后者更新?
  2. 如果listen 没有设置为false,widget 会默认重建还是不重建?如果 listen 设置为 true 会怎样?
  3. 当我们有 Consumer 时,为什么 Provider.of 可以选择重建 UI?
  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?

推荐答案

没关系.但要快速解释一下:

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

Provider.of 是获取和监听对象的唯一方式.ConsumerSelector 和所有 *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.ofConsumer 是个人喜好的问题.但两者都有一些论据

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

  • 可以在所有小部件生命周期中调用,包括点击处理程序和didChangeDependencies
  • 不会增加缩进
  • 允许更精细的小部件重建
  • 解决大部分 BuildContext 误用问题

这篇关于何时使用 Provider.of&lt;X&gt;与消费者 X 对比在颤振中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆