我尝试将 Cubit 与相应的状态类一起使用,如果我省略关键字 required,Android studio 会在状态类构造函数中引发错误。我只是想了解为什么?
这是来自 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来做到这一点吗?当前值;
另一个潜在的解决方案是更改您的构造函数:
CounterState(this.currentValue);
(注意缺少大括号)
关于flutter - 为什么这个 Flutter Cubit 在省略关键字 'required' 时会抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70501573/