Im New In Flutter, and developing an app that can be used by public user or apartment occupants.
The new flutter force me to add required or other null safety thing.
and i got error type ‘I/flutter (12174): type ‘Null’ is not a subtype of type ‘String’
is there anyway to use nullable String without downgrading my flutter?
Json/API Output
"status": true,
"message": "Sign Up Success",
"data": [
{
"id": "2042",
"email": "user@domain.com",
"id_apartment": null,
}
]
Model.dart
class UserModel {
late String id;
late String email;
late String id_apartment,;
UserModel({
required this.id,
required this.email,
required this.id_apartment,
});
UserModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
email = json['email'];
id_apartment= json['id_apartment'];
}
Map<String, dynamic> toJson() {
return {
'id': id,
'email': email,
'id_apartment': id_apartment,
};
}
}
Service.dart
if (response.statusCode == 200) {
var data = jsonDecode(response.body)['data'];
UserModel user = UserModel.fromJson(data[0]);
return user;
} else {
throw Exception('Sign Up Failed');
}
>Solution :
change your model class declaration with null-able value and remove the late keywords
class UserModel {
String? id;
String? email;
String? id_apartment,;
UserModel({
required this.id,
required this.email,
required this.id_apartment,
});
UserModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
email = json['email'];
id_apartment= json['id_apartment'];
}
Map<String, dynamic> toJson() {
return {
'id': id,
'email': email,
'id_apartment': id_apartment,
};
}
}