Back to results for “Generics”
Flutter › State Management with Riverpod

How does StateNotifierProvider let you properly manage genuinely more complex state that requires several genuinely separate distinct methods for updating it, compared to the considerably simpler StateProvider?

Intermediate

Answer

StateNotifierProvider works together with a StateNotifier subclass, letting you properly define several genuinely separate distinct named methods for updating that particular provider's own held state, such as addItem and removeItem on a genuine shopping cart, rather than the considerably simpler StateProvider, which is generally genuinely best suited for a fairly simple piece of state that only ever genuinely needs to be directly and simply reassigned, and this particular pattern provides a genuinely clean, well organized location specifically for containing genuinely more complex business logic related to updating that particular given piece of state.
class CartNotifier extends StateNotifier<List<String>> {
  CartNotifier() : super([]);
  void addItem(String item) => state = [...state, item];
}

final cartProvider = StateNotifierProvider<CartNotifier, List<String>>((ref) => CartNotifier());
Real-world example A shopping cart feature uses StateNotifierProvider together with a dedicated CartNotifier class exposing genuinely clear, well named addItem and removeItem methods, keeping that particular cart's own update logic properly organized and cleanly separate from the actual widget code itself.

Common follow-ups: How does StateNotifierProvider genuinely compare to the considerably newer code generation based Notifier class?;What genuinely happens if you try to directly mutate a StateNotifier's own held state without properly going through one of its own defined methods?