4
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

Likhith M
  • 41
  • 2
  • 6
  • 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. – Midhun MP Apr 29 '22 at 08:34

2 Answers2

5

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);
nagendra nag
  • 1,142
  • 2
  • 15
4

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;
        },
      ),
    );
  }
}
Josteve
  • 11,459
  • 1
  • 23
  • 35