Where should you place the state value in Riverpod?

Issue

To access the state of a StateProvider or StateNotifierProvider:

Sometimes in the Riverpod documentation, the state variable is added after the watch function.

int count = watch(counterProvider).state;

However, my code where I am using a StateNotifier, works only if I refer to it inside watch. i.e

watch(myNotifier.state)

What are the differences?

Solution

The widget that is consuming the provider will behave differently in the two cases.

In the first case:

watch(counterProvider).state

The consumer will look at the entire counterProvider and it will be rebuilt if anything causes a NotifyProvider.

In second case:

watch(counterProvider.state)

The consumer is looking at the state variable only and it will only be rebuilt if the state changes and cause a NotifyProvider.

Answered By – L. Gangemi

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.