小编典典

Provider.of(context,listen:false)是否等同于context.read()?

flutter

// 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()可以正常工作时却出现此错误?

尝试在提供程序context.read<Model>build方法或update回调内部使用。


阅读 1632

收藏
2020-08-31

共1个答案

小编典典

好吧,他们不一样。

您不应该readbuild方法内部使用。相反,坚持旧的是金色图案:

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-08-31