在 flutter 中使用 Riverpod 无法收听状态更新

Trouble listening for updates in state with using Riverpod in flutter

尝试通过构建 flutter 计数器应用程序并使用 StateNotifierProvider 更新计数来学习 riverpod。问题是我无法更新计数。这是我所有的代码。

状态class:

class CounterState{
  int count;

  CounterState({this.count = 0});

  CounterState copyWith({required int updatedCounter}) =>
      CounterState(count: updatedCounter);
}

StateNotifierStateNotifierProvider

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),
      ),
    );
  }
}

为什么 UI 上的计数在 StateNotifier class

上更新时没有更新

您的 currentCount 方法不会随新状态而改变。删除它并在您的小部件中执行此操作

ref.watch(counterProvider).count.toString(),