// 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.
listen: false will not cause widgets to rebuild when the value changes. If your widgets still rebuild with listen: false , then it is likely that even without the call to Provider. of , your widget would still rebuild. This can happen if the parent of your widget rebuilds too.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With