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 thebuild
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?