11

In the Riverpod documentation it says:

That's where context.read(myProvider) is a solution.

Using it, we could refactor our previous code to:

@override 
Widget build(BuildContext context) {   
  return RaisedButton(
    onPressed: () => context.read(counterProvider).state++,
    child: Text('increment'),
  ); 
} 

By doing so, clicking on our button still increments the counter. But we are no-longer listening to the provider, which avoids unnecessary rebuilds.

But then it says:

caution

Avoid calling context.read inside the build method of a Widget. If you want to optimize rebuilds, extract the value listened in a Provider instead.

This is a little confusing to me. First the documentation gives an example of using context.read inside the build method and then it gives a warning to avoid it. Why?

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • 2
    Does this answer your question? [Flutter Riverpod - using read() inside build method](https://stackoverflow.com/questions/64253162/flutter-riverpod-using-read-inside-build-method) – Alex Hartford Oct 12 '20 at 15:47

1 Answers1

8

The build method can be called multiple times during layout. Thus you should avoid doing any extra work inside it (like calling a method on your model).

However, the onPressed callback of the RaisedButton doesn't actually get called when build is called. onPressed is only called when the user presses the button. Only then will Riverpod read your provider and call the method on the model. So the warning in the documentation doesn't apply in that situation.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • 1
    Do you know what an example of `extract the value listened in a Provider instead` would look like? As to me it seems like in the docs they always read providers inside the build method if reading from inside a widget. I fail to see how using `watch` inside the build method is a better solution. Could it mean to use ProviderContainer().read() from within the widget, but outside of the build method? – BeniaminoBaggins Jul 16 '21 at 23:18
  • @BeniaminoBaggins, That's a good question. I'm a little unclear on that myself, too. – Suragch Jul 17 '21 at 03:34