将api调用映射到flutter中的模型类



我知道这可能是基本的,但我是Flutter的新手。我创建了一个模型类来映射我从API接收的数据。模型类看起来像这样:

class item{
final String id;
final String description;
final List<String> images;
}

API调用返回这个json:

"item" : {
"id": "abc",
"description": "xyz",
"images": [
{
"link": "https//............jpeg",
"id": "123546",
"zoomable": true,
}

{
"link": "https//............jpeg",
"id": "45876",
"zoomable": true,
}
]

}

我正在使用:

Item.fromJson(Map<String>, dynamic parsedJson)
{
id: parsedJson["item"]['id']
images: parsedJson['item']['images']
}

以将API数据映射到我的模型类,但我不希望图像列表中的所有信息;所有链接";。知道如何提取所有这些吗?谢谢

您可能需要使用此->https://app.quicktype.io/(QuickType(。在那里,您可以轻松地创建类模型,然后可以在API调用中使用它们来获取任何类型的数据。[创建模型时请选择飞镖]

就像在你上面的情况下,模型会是这样的:

// To parse this JSON data, do
//
//     final asf = asfFromJson(jsonString);
import 'dart:convert';
Asf asfFromJson(String str) => Asf.fromJson(json.decode(str));
String asfToJson(Asf data) => json.encode(data.toJson());
class Asf {
Asf({
this.item,
});
Item item;
factory Asf.fromJson(Map<String, dynamic> json) => Asf(
item: json["item"] == null ? null : Item.fromJson(json["item"]),
);
Map<String, dynamic> toJson() => {
"item": item == null ? null : item.toJson(),
};
}
class Item {
Item({
this.id,
this.description,
this.images,
});
String id;
String description;
List<Image> images;
factory Item.fromJson(Map<String, dynamic> json) => Item(
id: json["id"] == null ? null : json["id"],
description: json["description"] == null ? null : json["description"],
images: json["images"] == null ? null : List<Image>.from(json["images"].map((x) => Image.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"description": description == null ? null : description,
"images": images == null ? null : List<dynamic>.from(images.map((x) => x.toJson())),
};
}
class Image {
Image({
this.link,
this.id,
this.zoomable,
});
String link;
String id;
bool zoomable;
factory Image.fromJson(Map<String, dynamic> json) => Image(
link: json["link"] == null ? null : json["link"],
id: json["id"] == null ? null : json["id"],
zoomable: json["zoomable"] == null ? null : json["zoomable"],
);
Map<String, dynamic> toJson() => {
"link": link == null ? null : link,
"id": id == null ? null : id,
"zoomable": zoomable == null ? null : zoomable,
};
}

parsedJson['item']['images']List<Map<String, dynamic>>,您更希望将其作为List<String>。使用Listmap方法,并提供一个从json映射中提取字符串的函数。

final strings = parsedJson['item']['images']
.map<String>((e) => e['link'] as String)
.toList();

在第二行中,map<String>返回一个Iterable<String>,并接受一个必须返回String的函数。该函数取元素e,我们知道它将是Map<String, dynamic>,并提取与关键字link相关联的值。

在第三行中,CCD_ 12将可迭代项转换为列表。

因此stringsList<String>

最新更新