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

2

8
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

Rimskykorsakov answered 29/4, 2022 at 8:29 Comment(1)
If you check the riverpod in pub.dev, they have given an example for Counter app which is what you are looking for. You can follow that approach.Awad
S
9

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;
        },
      ),
    );
  }
}
Stole answered 29/4, 2022 at 9:15 Comment(1)
.state from (itemCountProvider.state) is now deprecated use (itemCountProvider.notifier)Patroon
C
9

You can update the state with read

  1. If you want to update a new value every time
ref.read(itemCountProvider.state).state = newValue;
  1. If you want 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);
Clamp answered 29/4, 2022 at 9:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.