Home > Mobile >  Why and How I should use StateNotifierProvider in RiverPod?
Why and How I should use StateNotifierProvider in RiverPod?

Time:10-25

I know StateProvider is used for immutable states like counter value.But I couldn't understand StateNotifierProvider.Why and How I should StateNotifierProvider in my apps?

CodePudding user response:

StateNotifierProvider is a good interface when a single state wants to be consumed for changes, and updated via method calls on its underlying notifier, encouraged to treat state as an immutable.

If your problem fits that, this provider is the best.

Some patterns call for a bit less rigor in updating the state, and for those a StateProvider can provide a read/write variable that still has notification wiring and the possibility of consuming other providers to give its value. A StateProvider still has an underlying notifier, but this notifier isn't subclassed with additional behavior as a StateNotifier would have been, enroute to the StateNotifierProvider.

CodePudding user response:

If suddenly your state becomes more complex than true and false, you should use StateNotifierProvider. You can put methods in the StateNotifier class to handle your state. For example, adding or removing items from your state-List are two separate methods that you can no longer implement in StateProvider

  • Related