为什么这个 Flutter Cubit 省略关键字 'required' 会报错?

Why does this Flutter Cubit throw an error when the keyword 'required' is omitted?

我正在尝试使用具有相应状态 class 的 Cubit,如果我省略关键字 required,Android 工作室会在状态 class 构造函数中抛出错误。我只是想了解为什么?

这是来自 counter_cubit.dart

的代码
class CounterCubit extends Cubit<CounterState> {
  CounterCubit() : super(CounterState(currentValue: 0));

  void increment() => emit(CounterState(currentValue: state.currentValue +1));

}

这是来自 counter_state.dart

的代码
class CounterState<int> {
  int currentValue;
  CounterState({required this.currentValue});
}

为什么在这个用例的构造函数中需要 required 关键字?

我在 Android Studio v Arctic Fox 2020.3.1 中工作,使用 Flutter v2.5.3、Dart v2.14.4、flutter_bloc:^8.0.0 和 bloc:^8.0 .0

谢谢

这是因为 currentValue 未标记为可为空。

您可以通过 int? currentValue;

另一个可能的解决方案是更改您的构造函数:

CounterState(this.currentValue);(注意缺少的大括号)