Search code examples
flutterflutter-providerflutter-stateriverpod

Where should you place the state value in Riverpod?


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.