【问题标题】:What is the difference between between context.watch and context.read in flutter_bloc?flutter_bloc 中的 context.watch 和 context.read 有什么区别?
【发布时间】:2021-12-16 19:37:23
【问题描述】:

我只是在扑腾中了解到一肘。我在教程视频中学习,所以在那个视频中,导师制作了一个登录页面,其中包含一个电子邮件和密码文本字段以及一个登录按钮。在那段视频中,导师仍然使用旧版本的flutter_bloc。当我遵循其中一条代码行时出现警告

child: ElevatedButton(
  onPressed: () {
    context.watch<AuthCubit>().signIn(
     _emailController.text,
     _passwordController.text);
}

该代码写在 onPressed 功能按钮内。 它说context.bloc 已被弃用。当我尝试运行该应用程序时,它返回一个错误,因为我使用的 flutter_bloc 版本不支持 null 安全,所以我将它升级到当前版本(7.3.1),我在 6.1.0 版本更新日志中找到了这个(你可以看到它在flutter_bloc change log)

deprecated: context.bloc in favor of context.read and context.watch

因为我不知道有什么区别,所以我只是将context.bloc 更改为context.watch 然后我再次运行该应用程序并返回另一个错误

Tried to listen to a value exposed with a provider, from outside of the widget tree.

This is likely caused by an event handler (like a button's onPressed) that called
Provider.of without passing `listen: false`.

To fix, write:
Provider.of<AuthCubit>(context, listen: false);

It is unsupported because may pointlessly rebuild the widget associated to the
the event handler, when the widget tree doesn't care about the value.
...

当我将其更改为 context.read 时,它可以工作。我想知道它们之间的区别

【问题讨论】:

    标签: android flutter mobile flutter-bloc flutter-cubit


    【解决方案1】:

    context.watch&lt;T&gt;() 监听 T 上的变化

    context.read&lt;T&gt;() 不听就返回 T

    你在打电话

    context.watch<AuthCubit>().signIn(
         _emailController.text,
         _passwordController.text);
    

    ElevatedButton's onPressed() 中,从而从小部件树外部监听AuthCubit 与提供程序公开。当您将其更改为使用 context.read&lt;AuthCubit&gt; 时,您将返回 AuthCubit 而不会从小部件树外部收听它。

    【讨论】:

    • 谢谢你的回答,但我还有一些问题。 “外部小部件树”是什么意思?是 BlocProvider 之外的小部件还是什么?
    • @AlunParanggi 来自提供程序包的这个问题讨论了“外部小部件树”的含义以及为什么应该避免在小部件树之外收听
    猜你喜欢
    • 1970-01-01
    • 2010-10-02
    • 2011-12-12
    • 2010-09-16
    • 2012-03-14
    • 2012-02-06
    • 2011-02-25
    • 2011-11-22
    • 2015-03-26
    相关资源
    最近更新 更多