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>();
它们是否相同?如果是,那么为什么当我在 build()
方法中使用 read
时会出现此错误,而 Provider.of()
有效?
Tried to use context.read<Model>
inside either a build
method or the update
callback of a provider.
final model = context.read<Model>();
这个 returns 模型没有监听任何变化。
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>();
相同
建议:
使用 context.read()
、context.watch()
而不是 Provider.of()
。
如需更多见解,请参阅this, this & this。
嗯,它们不一样。
您不应在 build
方法中使用 read
。而是坚持旧的是黄金模式:
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
}
context.read<T>()
内部 returns Provider.of<T>(context, listen: false)
.
目前,请使用您认为最好的或您喜欢的那个。
这是Provider中read的实现:
extension ReadContext on BuildContext {
T read<T>() {
return Provider.of<T>(this, listen: false);
}
}
// 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>();
它们是否相同?如果是,那么为什么当我在 build()
方法中使用 read
时会出现此错误,而 Provider.of()
有效?
Tried to use
context.read<Model>
inside either abuild
method or theupdate
callback of a provider.
final model = context.read<Model>();
这个 returns 模型没有监听任何变化。
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>();
建议:
使用 context.read()
、context.watch()
而不是 Provider.of()
。
如需更多见解,请参阅this, this & this。
嗯,它们不一样。
您不应在 build
方法中使用 read
。而是坚持旧的是黄金模式:
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
}
context.read<T>()
内部 returns Provider.of<T>(context, listen: false)
.
目前,请使用您认为最好的或您喜欢的那个。
这是Provider中read的实现:
extension ReadContext on BuildContext {
T read<T>() {
return Provider.of<T>(this, listen: false);
}
}