Is Provider.of(context, listen: false) equivalent to context.read()?

前提是你 提交于 2020-06-28 03:51:36

问题


// 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>();

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?

Tried to use context.read<Model> inside either a build method or the update callback of a provider.


回答1:


Well, they aren't the same.

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



回答2:


final model = context.read<Model>();
This returns the Model without listening for any changes.

final model = context.watch<Model>();
This makes the widget listen for changes on the Model.

final model = Provider.of<Model>(context, listen: false);
This works the same as context.read<Model>();

final model = Provider.of<Model>(context);
This works the same as context.watch<Model>();

Recommendations:
Use context.read(), context.watch() instead of Provider.of(). For more insights, refer to this, this & this.




回答3:


Well I don't know about context.read<Model>, but Provider.of<Model>(context, listen: false); is used for example if you want to call a function inside your Model class without listening to any changes. You can avoid rebuilding your app with that approach and still call functions from your Model.



来源:https://stackoverflow.com/questions/62257064/is-provider-ofcontext-listen-false-equivalent-to-context-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!