问题
// 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 abuild
method or theupdate
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