Flutter Riverpod - 带有 StateNotifierProvider 和模型的复选框,它是如何工作的

问题描述 投票:0回答:1

我有一个模型,它是一个蓝图,在我通过 HTTP 发送它之前需要填充它。该模型包含一个布尔值:

class ReportBugModel {
  bool isReproductive;
  ReportBugModel({
    this.isReproductive = false,
  }) ;

  ReportBugModel copyWith({
    bool? isReproductive,
}) {
    return ReportBugModel(
      isReproductive: isReproductive ?? this.isReproductive,
    );
  }
}

然后我有一个带有此模型的 StateNotifer:

class FillReportBugModelNotifier extends StateNotifier<ReportBugModel> {
  FillReportBugModelNotifier() : super(ReportBugModel());
  void toggleReproductive() {
    print("inside toggle");
    state = state.copyWith(isReproductive: !state.isReproductive);
  }
}

final fillErrorModelProvider = StateNotifierProvider<FillReportBugModelNotifier, ReportBugModel>((ref) {
  return FillReportBugModelNotifier();
});

我的小部件内部现在出现问题:

class _AdditionalInfoScreenState extends ConsumerState<AdditionalInfoScreen> {

  @override
  Widget build(BuildContext context) {
    final isChecked = ref.watch(fillErrorModelProvider).isReproductive;
    print(isChecked);

 return Stack(
      children: [
//...
CheckboxListTile(
value: isChecked,
 onChanged: (bool? value) {
                         ref.read(fillErrorModelProvider.notifier).toggleReproductive();
                        },

如您所见,我添加了一条打印语句,这是热重启并单击复选框两次后的输出(预期输出应该是: false -> true,然后 true -> false”:

"Restarted application in 232ms.
false
false
false
inside toggle
true
false
inside toggle
true"

所以这是一种奇怪的行为,我无法解释,就像它切换得非常快,但我只点击一次。我做错了什么?

flutter dart state riverpod
1个回答
0
投票

使您的

ReportBugModel
模型不可变并重复这些步骤。
StateNotifier
必须基于不可变数据,即模型中具有
final
字段,并且状态更改基于全新的对象。为了更容易实现,请使用
freezed
包,因为这将为您生成
copyWith
方法和正确的
hashCode
/
operator ==

© www.soinside.com 2019 - 2024. All rights reserved.