Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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));

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

It’s because currentValue is not marked as nullable.

You can do this by int? currentValue;

Another potential solution, would be to change your constructor:

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading