[英]Flutter(Dart) - How to read from a list in a list?
所以我有这种格式的数据:
List users = [
{
"id": "p1",
"name": "John Doe",
"age": "44",
"imageUrl": [
{
"assets/images/anastasia-vityukova-unsplash-blackandwhiteimage.png",
"assets/images/anastasia-vityukova-unsplash.png",
}
],
"profession": "Financial Consultant"
},
{
"id": "p2",
"name": "John Doe2",
"age": "42",
"imageUrl": [
{
"assets/images/good-faces-hiba-unsplash-blackandwhiteimage.png",
"assets/images/good-faces-hiba-unsplash.jpg",
}
],
"profession": "Financial Consultant"
},
];
如何读取 imageUrls?
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(lstUsers[index]["imageUrl"][0]),
fit: BoxFit.cover),
),
正如错误所说, Dart 将该字段视为 Set {}
或更具体地说是LinkedHashSet
。 集合不实现[]
运算符,但您可以使用方法elementAt
访问其元素。
lstUsers[0]["imageUrl"][0].elementAt(1)
在lstUsers[0]["imageUrl"][0]
之前,您已经选择了数组中的第一个元素,但请注意,该数组不仅由字符串组成,而且是其中包含字符串的集合。
[{ "assets/images/anastasia-vityukova-unsplash-blackandwhiteimage.png",
"assets/images/anastasia-vityukova-unsplash.png", }]
这就是您必须使用.elementAt()
来访问字符串的原因。 如果您有能力放弃字符串周围的{}
,我会建议您更容易访问它们。 或者甚至更好地创建管理 JSON 的序列化和反序列化的类。一个不错的起点是quicktype 。
您可以看到 imageUrl 数组的结构如下:
"imageUrl": [
{
"assets/images/good-faces-hiba-unsplash-blackandwhiteimage.png",
"assets/images/good-faces-hiba-unsplash.jpg",
}
],
imageUrl 数组中的第一项不是字符串,而是一个集合(因为它被花括号括起来)。 如果您想访问 imageUrl 列表中的第一个资产,请删除花括号并使 imageUrl 看起来像这样:
"imageUrl": [
"assets/images/good-faces-hiba-unsplash-blackandwhiteimage.png",
"assets/images/good-faces-hiba-unsplash.jpg",
],
// Now when you use that it will return a String
lstUsers[index]["imageUrl"][0];
如果你想保持列表的结构不变,但你仍然想访问第一个 imageUrl,你可以使用以下语法:
lstUsers[index]["imageUrl"][0].first;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.