Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Riverpod context.read vs Provider in the build method

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?

like image 293
Suragch Avatar asked Oct 10 '20 09:10

Suragch


People also ask

Is Riverpod better than provider?

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.

What is ref in Riverpod?

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.

What is ProviderScope in Flutter?

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.


1 Answers

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.

like image 53
Suragch Avatar answered Nov 10 '22 07:11

Suragch