skip to Main Content
final filterProvider = StateProvider<List<Map>>((ref) => [
      {'text': 'rating', 'onOrOff': true},
      {'text': 'km', 'onOrOff': true},
    ]);

I have this filterProvider. And I am trying to update the value of ‘onOrOff’.

ref.watch(filterProvider.notifier).state[i]['onOrOff'] = onOffVal;

When I do this way, Riverpod does not change the value immediately, how can I adjust the value and make Riverpod to apply changes right away?

2

Answers


  1. In riverpod the state provided with a StateProvider is supposed to be immutable. You cannot modify it, you need to re-assign it.

    You can read

    It is typically used for:

    • exposing an immutable state which can change over time after reacting to custom events.
    • centralizing the logic for modifying some state (aka "business logic") in a single place, improving maintainability over time.

    in riverpod’s documentation

    final filter = [...ref.read(filterProvider)]; // Copies the list.
    filter[i]['onOrOff'] = onOffVal;
    ref.read(filterProvider.notifier).state = filter;
    
    Login or Signup to reply.
  2. This is part of why StateNotifier and StateProvider should not be used in modern Riverpod applications. Instead, you should be constructing a Notifier-based provider, and provide mutation methods to update your state. The Notifier can use combinations of assigning to state (as the previous StateNotifier did) and/or calling ref.notifyListeners() (as the previous ChangeNotifier did).

    But please, stop using StateNotifier, ChangeNotifier, and StateProvider with Riverpod! They are all effectively deprecated.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search