簡體   English   中英

flutter_bloc 中的 context.watch 和 context.read 有什么區別?

[英]What is the difference between between context.watch and context.read in flutter_bloc?

我只是在顫動中了解到一肘。 我在教程視頻中學習,因此在該視頻中,導師制作了一個登錄頁面,其中包含一個電子郵件和密碼文本字段以及一個登錄按鈕。 在那個視頻中,導師仍然使用舊版本的 flutter_bloc。 當我遵循其中一行代碼時出現警告

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

該代碼寫在 onPressed 功能按鈕內。 它說context.bloc已被棄用。 當我嘗試運行該應用程序時,它返回一個錯誤,因為我使用的 flutter_bloc 版本不支持空安全,因此我將其升級到當前版本 (7.3.1) 並在 6.1.0 版更改日志中找到了它(您可以看到它在flutter_bloc 更改日志中

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它會起作用。 我想知道它們之間的區別

context.watch<T>()監聽 T 上的變化

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

你打電話

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

ElevatedButton's onPressed() ,從而AuthCubit部件樹的外部偵聽通過提供程序公開的AuthCubit 當您將其更改為使用context.read<AuthCubit>您將返回AuthCubit而無需從小部件樹外部監聽它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM