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

时间:2020-06-08 07:30:33

标签: flutter flutter-provider

// 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

4 个答案:

答案 0 :(得分:5)

// @ts-ignore
这将返回模型,而无需侦听任何更改。

this.x
这使小部件可以监听模型上的更改。

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>();而不是context.read()有关更多见解,请参阅thisthisthis

答案 1 :(得分:5)

嗯,它们不一样。

您不应该在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
}

答案 2 :(得分:0)

context.read<T>() 内部返回 Provider.of<T>(context, listen: false)

目前,使用您认为最好的或您喜欢的那个。

这是Provider中read的实现:

extension ReadContext on BuildContext {
  T read<T>() {
    return Provider.of<T>(this, listen: false);
  }
}

答案 3 :(得分:-1)

我不了解context.read<Model>,但是例如,如果您想在Model类内部调用一个函数而不听任何更改,则使用Provider.of<Model>(context, listen: false);。您可以避免使用这种方法重建应用,而仍然可以从模型中调用函数。