【发布时间】:2021-12-15 12:20:48
【问题描述】:
尝试通过构建颤振计数器应用程序并使用StateNotifierProvider 来更新计数来学习riverpod。问题是我无法更新计数。这是我所有的代码。
状态类:
class CounterState{
int count;
CounterState({this.count = 0});
CounterState copyWith({required int updatedCounter}) =>
CounterState(count: updatedCounter);
}
StateNotifier 和 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
}
}
我的 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),
),
);
}
}
为什么在 StateNotifier 类上更新计数时 UI 上没有更新
【问题讨论】: