【发布时间】:2022-09-29 23:07:46
【问题描述】:
我有从服务器收到的数据。我通过了有 froJson, toJson 方法的模型。在 toJson 方法中,我遇到了问题。当我想将数据转换回 Json 时,出现错误(我附上了下面的屏幕截图)。告诉我如何解决这个问题,以便数据一切正常,我可以将它们转换为 Json?
主模型
class MainModel {
String name;
List<AmenitiesModel>? amenities;
List<DeviceModel>? devices;
List<PhotoModel>? photos;
MainModel ({
required this.name,
this.amenities,
this.devices,
this.photos,
});
factory MainModel .fromJson(Map<String, dynamic> json) =>
MainModel(
id: json[\'id\'],
name: json[\'name\'],
amenities: json[\'amenities\'] != null
? List<AmenitiesModel>.from(
json[\'amenities\'].map(
(item) => AmenitiesModel.fromJson(item),
),
).toList()
: null,
user: json[\'user\'] != null ? User.fromJson(json[\'user\']) : null,
devices: json[\'devices\'] != null
? List<PublicChargingDeviceModel>.from(
json[\'devices\'].map(
(item) => DeviceModel.fromJson(item),
),
).toList()
: null,
photos: json[\'gallery\'] != null
? List<PhotoModel>.from(
json[\'gallery\'].map(
(item) => PhotoModel.fromJson(item),
),
).toList()
: null);
Map<String, dynamic> toJson() {
return {
\'name\': name,
\'amenities\': amenities!.map((e) => e.toJson()).toList(),
\'devices\': devices?.map((e) => e.toJson()).toList(),
\'gallery\': photos?.map((e) => e.toJson()).toList(),
};
}
便利设施型号
class AmenitiesModel {
String name;
final String type;
AmenitiesModel({required this.type, required this.name});
factory AmenitiesModel.fromJson(Map<String, dynamic> json) {
return AmenitiesModel(
type: json[\'type\'],
name: json[\'name\'],
);
}
Map<String, dynamic> toJson() {
return {
if (type == \'other\') \'name\': name,
\'type\': type,
};
}
错误
标签: flutter dart dart-null-safety