// 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>();他们是一样的还是不一样的?如果它们是,那么当我在read方法中使用build()方法时,当Provider.of()工作时,为什么要得到这个错误呢?
尝试在
build方法或提供程序的update回调中使用update。
发布于 2020-06-12 16:04:30
嗯,他们不一样。
您不应该在read方法中使用build。相反,坚持旧的是黄金模式:
final model = Provider.of<Model>(context, listen: false); 当您想要在回调中使用上述模式时,可以使用read,例如,当按下按钮时,我们可以说它们都在执行相同的操作。
onPressed: () {
final model = context.read<Model>(); // recommended
final model = Provider.of<Model>(context, listen: false); // works too
}发布于 2020-06-11 17:47:30
final model = context.read<Model>();
这将返回模型,而不会侦听任何更改。
final model = context.watch<Model>();
这使得小部件侦听模型上的更改。
final model = Provider.of<Model>(context, listen: false);
这与context.read<Model>();的工作原理相同
final model = Provider.of<Model>(context);
这与context.watch<Model>();的工作原理相同
Recommendations:
使用context.read(),context.watch()而不是Provider.of()。关于的更多见解,,请参考这,这 & 这。
发布于 2021-08-03 16:28:20
context.read<T>()内部返回Provider.of<T>(context, listen: false)。
现在,用你认为最好的或者你喜欢的那个。
这是read in Provider的实现:
extension ReadContext on BuildContext {
T read<T>() {
return Provider.of<T>(this, listen: false);
}
}https://stackoverflow.com/questions/62257064
复制相似问题