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?
In the flutter community, many developers think Riverpod is better than Provider, which is an earlier-released-state-management package. However, flutter creators still recommend Provider as the stable state management mechanism at the time of writing this post.
ref. watch is used inside the build method of a widget or inside the body of a provider to have the widget/provider listen to a provider: For example, a provider could use ref. watch to combine multiple providers into a new value. An example would be filtering a todo-list.
ProviderScope class Null safetyA widget that stores the state of providers. All Flutter applications using Riverpod must contain a ProviderScope at the root of their widget tree.
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.
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