简体   繁体   中英

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

I am attempting to use a Cubit with a corresponding state class and Android studio throws an error in the state class constructor if I omit the keyword, required. I'm just trying to understand why?

Here is the code from counter_cubit.dart

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

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

}

Here is the code from the counter_state.dart

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

Why is the required keyword needed in the constructor in this use case?

I'm working in Android Studio v Arctic Fox 2020.3.1, using Flutter v2.5.3, Dart v2.14.4, flutter_bloc: ^8.0.0, and bloc: ^8.0.0

Thanks

It's because currentValue is not marked as nullable.

You can do this by int? currentValue; int? currentValue;

Another potential solution, would be to change your constructor:

CounterState(this.currentValue); (note the missing curly braces)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM