当我解析我的嵌套json时,我的模型中的媒体类可能是空的,我不能检查它是否为空,并且我不能Map我的嵌套元素到我的模型中:
class Product {
Product({
required this.id,
required this.name,
required this.categoryName,
this.media,
});
late final int id;
late final String name;
late final String categoryName;
List<Media>? media;
Product.fromJson(Map<String, dynamic> json){
id = json['id'];
name = json['name'];
categoryName = json['category_name'];
media != null ? (json["media"] as List).map((a) => Media.fromJson(a)).toList() : null;
// media != null ? List.from(json['media']).map((e)=>Media.fromJson(e)).toList() : null;
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['id'] = id;
data['name'] = name;
data['category_name'] = categoryName;
data['media'] = media!.map((e)=>e.toJson()).toList();
return data;
}
}
class Media {
Media({
required this.id,
required this.productId,
required this.type,
required this.links,
});
late final int id;
late final int productId;
late final String type;
late final Links links;
Media.fromJson(Map<String, dynamic> json){
id = json['id'];
productId = json['product_id'];
type = json['type'];
links = Links.fromJson(json['links']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['product_id'] = productId;
_data['type'] = type;
_data['links'] = links.toJson();
return _data;
}
}
当我尝试用forEach循环它时,我得到:
错误:参数类型'Media'不能赋值给参数类型'Map〈String,dynamic〉'。(参数类型_not_assignable at [yiwumart] lib/catalog_screens/catalog_item.dart:72)
final media = productItem.media!.map((e) => Media.fromJson(e)).toList();
1条答案
按热度按时间k3bvogb11#
尝试