我是 Flutter 的新手,正在開發一個可供公共用戶或公寓居住者使用的應用程式。新的顫振迫使我添加必需的或其他空安全的東西。
我得到了錯誤型別“I/flutter (12174): type 'Null' is not a subtype of type 'String'
有沒有辦法在不降級我的顫振的情況下使用可為空的字串?
JSON/API 輸出
"status": true,
"message": "Sign Up Success",
"data": [
{
"id": "2042",
"email": "[email protected]",
"id_apartment": null,
}
]
模型.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,
};
}
}
服務.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');
}
uj5u.com熱心網友回復:
使用可為空的值更改您的模型類宣告并洗掉后期關鍵字
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,
};
}
}
uj5u.com熱心網友回復:
請參考以下代碼
id = json['id'] ?? "";
email = json['email'] ?? "";
id_apartment= json['id_apartment'] ?? "";
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,
};
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/377970.html
