'Is there a way to update the value of state provider in river pod after declaring it

final itemCountProvider = StateProvider<int>((ref) {
  return 0;
});

i need to keep track of number of items selected in my project initially the item count would be zero but later on i need to give it the calculated value how to update the value in itemCountProvider as it is already declared final



Solution 1:[1]

You can update the value of state provider like so:

ref.read(itemCountProvider.state).state = 10;

Here is an example counter app:

final itemCountProvider = StateProvider((ref) => 0);
class HomePage extends ConsumerWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final counter = ref.watch(itemCountProvider);
    return Scaffold(
      body: Center(
        child: Text(
          counter.toString(),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          ref.read(counterProvider.state).state += 1;
        },
      ),
    );
  }
}

Solution 2:[2]

You can update the state with read

  1. if you want to update new value every time
ref.read(itemCountProvider.state).state = newValue;
  1. if you to update based previous state value
ref.read(itemCountProvider.state).state = ref.read(itemCountProvider.state).state + newValue;

or

ref.read(itemCountProvider.state).state += newValue;

or

ref.read(counterProvider.notifier).update((state) => state + newValue);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Josteve
Solution 2 nagendra nag