Flutter Riverpod context.read vs Provider in the build method

4.7k views Asked by At

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?

1

There are 1 answers

2
Suragch On BEST ANSWER

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.