flutter_bloc 中 context.watch 和 context.read 有什么区别?

Alu*_*ono 9 mobile android flutter flutter-bloc flutter-cubit

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

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

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

deprecated: context.bloc in favor of context.read and context.watch
Run Code Online (Sandbox Code Playgroud)

因为我不知道区别,所以我只是更改context.bloccontext.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.
...
Run Code Online (Sandbox Code Playgroud)

当我将其更改为context.read有效时。我想知道它们之间的区别

Dan*_*iel 2

context.watch<T>()监听 T 上的变化

context.read<T>()返回 T 而不听它

你正在打电话

context.watch<AuthCubit>().signIn(
     _emailController.text,
     _passwordController.text);
Run Code Online (Sandbox Code Playgroud)

中,从而从小部件树外部ElevatedButton's onPressed()监听提供者公开的内容。AuthCubit当您将其更改为使用时,您无需从小部件树外部监听它即可context.read<AuthCubit>返回。AuthCubit