Provider.of(context,listen:false)是否等效于context.read()? [英] Is Provider.of(context, listen: false) equivalent to 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 abuild
method or theupdate
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屋!