Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 761
iDecode Avatar asked Jun 08 '20 07:06

iDecode


People also ask

What is listen false in 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.


2 Answers

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.

like image 67
Sanket Vekariya Avatar answered Oct 04 '22 21:10

Sanket Vekariya


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
}
like image 31
iDecode Avatar answered Oct 04 '22 21:10

iDecode