Issue
Trying to learn riverpod by building the flutter counter app and using a StateNotifierProvider
to update the count. The trouble is I can't get the count to update. Here is all of my code.
The state class:
class CounterState{
int count;
CounterState({this.count = 0});
CounterState copyWith({required int updatedCounter}) =>
CounterState(count: updatedCounter);
}
The StateNotifier
and StateNotifierProvider
final counterProvider = StateNotifierProvider<CounterController, CounterState>(
(ref) => CounterController(CounterState()));
class CounterController extends StateNotifier<CounterState>{
CounterController(CounterState state) : super(state);
int currentCount() => state.count;
void addCount(){
state = state.copyWith(updatedCounter: state.count+1);
debugPrint(state.count.toString()); // <-- prints the correct value of count
}
}
My ConsumerWidget:
class MyHomePage extends ConsumerWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
appBar: AppBar(
title: const Text("Riverpod counter"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
ref.watch(counterProvider.notifier).currentCount().toString(),
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: ref.read(counterProvider.notifier).addCount ,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
Why is the count not updating on the UI when it is getting updated on the StateNotifier
class
Solution
Your currentCount method does not change with the new state. Remove it and do this in your widget
ref.watch(counterProvider).count.toString(),
Answered By - Pris0n
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.