I've just updated Flutter and Dart and the following code no longer compiles. I understand it's to do with nulls, but not sure how to fix.
class DataCancelled {
bool cancelledOK;
DataCancelled({this.cancelledOK});
DataCancelled.fromJson(Map<String, dynamic> json) {
cancelledOK = json['value'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['value'] = this.cancelledOK;
return data;
}
}
The line "DataCancelled({this.cancelledOK});" has the following error: The parameter 'cancelledOK' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
And the line "DataCancelled.fromJson(Map<String, dynamic> json) {" has the following error: Non-nullable instance field 'cancelledOK' must be initialized. (Documentation) Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'.
What do I need to do to fix this?
CodePudding user response:
Either make cancelledOK
nullable like this bool? cancelledOk
or make it required like this required this.cancelledOK
CodePudding user response:
You either need to make cancelledOK optional by doing this :
bool? cancelledOK;
Or you need to add "required" keyword before this.cancelledOk in the constructor. This will solve your problem.
CodePudding user response:
If your member is required:
class DataCancelled {
late bool cancelledOK;
DataCancelled({required this.cancelledOK});
DataCancelled.fromJson(Map<String, dynamic> json) {
cancelledOK = json['value'];
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['value'] = cancelledOK;
return data;
}
}
If it is indeed optional:
class DataCancelled {
bool? cancelledOK;
DataCancelled({this.cancelledOK});
DataCancelled.fromJson(Map<String, dynamic> json) {
cancelledOK = json['value'];
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['value'] = cancelledOK;
return data;
}
}