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
CodePudding user response:
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;
},
),
);
}
}
CodePudding user response:
You can update the state with read
- if you want to update new value every time
ref.read(itemCountProvider.state).state = newValue;
- 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);