flutter - 为什么这个 Flutter Cubit 在省略关键字 'required' 时会抛出错误?

标签 flutter dart bloc

我尝试将 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/

相关文章:

flutter - 当使用 flutter_bloc 库在 Flutter 中推送新路由时,上下文无法正常工作

flutter - 如何在Flutter中将相同的BLoC用于不同的小部件?

firebase - 使用 Flutter 将 Firebase token 转换为字符串

flutter - 如何在 Flutter 中对齐单个小部件?

firebase - 在 Flutter App 中查找邮箱和用户名是否已经存在于 Firebase Auth 中

flutter - 如何在Flutter中替换GridView中的特定项目?

flutter - Flutter:SingleChildScrollView无法滚动

Flutter 插件未安装错误;运行时 'flutter doctor'

flutter - 无法从方法 'Null' 返回类型为 'onGenerateRoute' 的值,因为它的返回类型为 'Route<dynamic>'

dictionary - dart - map 值更改而无需明确设置