Provider.of(context,listen:false)是否等效于context.read()? [英] Is Provider.of(context, listen: false) equivalent to context.read()?

查看:429
本文介绍了Provider.of(context,listen:false)是否等效于context.read()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// Are these the same?
final model = Provider.of<Model>(context, listen: false); 
final model = context.read<Model>(); 

// Are these the same?
final model = Provider.of<Model>(context);
final model = context.watch<Model>();

它们是相同的还是不是?如果是,那么为什么在Provider.of()起作用的情况下在build()方法中使用read时出现此错误?

Are they the same or aren't they? If they are, then why do I get this error when I use read inside the build() method, while Provider.of() works?

试图在提供程序的build方法或update回调中使用context.read<Model>.

Tried to use context.read<Model> inside either a build method or the update callback of a provider.

推荐答案

嗯,它们不一样.

您不应在build方法内使用read.而是坚持使用古老的金色图案:

You shouldn't use read inside the build method. Instead stick to the old is gold pattern:

final model = Provider.of<Model>(context, listen: false); 

read用于要在回调中使用上述模式的情况,例如,当按下按钮时,可以说它们都在执行相同的操作.

read is used when you want to use the above pattern in a callback, for instance, when a button is pressed, then we can say they both are performing the same action.

onPressed: () {
  final model = context.read<Model>(); // recommended
  final model = Provider.of<Model>(context, listen: false); // works too
}

这篇关于Provider.of(context,listen:false)是否等效于context.read()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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