Home > Back-end >  Riverpod ref.watch(statenotifierprovider) vs ref.watch(statenotifierprovider.notifier)
Riverpod ref.watch(statenotifierprovider) vs ref.watch(statenotifierprovider.notifier)

Time:11-17

I've been trying to find out what is the difference between watching a StateNotifierPovider object vs watching the notifier exposed by it. As we can see in the docs following section watching the notifier object does not trigger the object's build method when the state is changed. Out of experimenting, it seems like watching the provider object exposes the state within the notifier just as ref.read(provider.notifier). state would. I can't really get the difference between directly watching the provider vs provider.notifier and why it does not trigger the build method when watching the notifier and changing its state.

CodePudding user response:

The documentation of .notifier should hopefully be clear about it:

Obtains the StateNotifier associated with this provider, without listening to state changes.

This is typically used to invoke methods on a StateNotifier. For example:

Button(
 onTap: () => ref.read(stateNotifierProvider.notifer).increment(),
)

This listenable will notify its notifiers if the StateNotifier instance changes. This may happen if the provider is refreshed or one of its dependencies has changes.

https://pub.dev/documentation/riverpod/latest/riverpod/AutoDisposeStateNotifierProvider/notifier.html

So ref.watch(provider) listens to state changes.

And ref.watch(provider.notifier) obtains the notifier only but does not listen to state change. Instead it listens to when the StateNotifier instance is recreated – such as if you did ref.refresh(provider), which would recreate the StateNotifier

  • Related