【问题标题】:Trouble listening for updates in state with using Riverpod in flutter在颤振中使用 Riverpod 无法监听状态更新
【发布时间】:2021-12-15 12:20:48
【问题描述】:

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

状态类:

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

为什么在 StateNotifier 类上更新计数时 UI 上没有更新

【问题讨论】:

    标签: flutter riverpod


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-11-19
      • 2021-05-23
      • 2020-08-04
      • 2021-06-01
      • 2021-10-21
      • 1970-01-01
      • 2022-11-12
      • 2021-03-11
      • 2018-12-26
      相关资源
      最近更新 更多