我正在尝试从数据来自 Firestore 的列表中显示 ListView.builder。我像这样获取并存储我的数据
List filterMangaList = [];
Future<List> getFavMangas() async {
var value = await firestore.collection("users").doc(user.uid).get();
final favMangasList = value.data()?["fav_manga"];
filterMangaList.clear();
for (var i in favMangasList) {
final mangas = await FirebaseFirestore.instance
.collection('mangas')
.where('title', isEqualTo: i)
.get();
final filterManga = mangas.docs.map((doc) => doc.data()).toList();
filterMangaList.add(filterManga);
}
return filterMangaList;
}
我要提取数据的列表是filterMangaList
,看起来像这样
[[{total_chapter: 361,图片:https://images.pexels.com/photos/213780/pexels-photo-213780.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500,标题:我的英雄学院}],[{total_chapter:700,图片:https://images.pexels.com/photos/213780/pexels-photo-213780.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500,标题:火影忍者}] ]
我的 ListView.builder 看起来像这样
FutureBuilder(
future: getFavMangas(),
builder: (context, AsyncSnapshot future) {
if (!future.hasData)
return Container();
else {
var filterMangaList = future.data;
print(filterMangaList);
return ListView.builder(
shrinkWrap: true,
itemCount: filterMangaList.length,
itemBuilder: (BuildContext context, int index) {
return Container(
child: Text(filterMangaList[index]["title"]),
);
},
);
}
}),
但是我有这个错误:
_TypeError (type 'String' is not a subtype of type 'int' of 'index')
我认为这是因为我有太多的[]
,但我不知道如何解决这个问题。
最佳答案
您的代码中实际上有一个[]
太少了。
这是你的数据结构
[
[{
total_chapter: 361,
pic: "https: //images.pexels.com/photos/213780/pexels-photo-213780.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
title: My Hero Academia
}],
[{
total_chapter: 700,
pic: "https://images.pexels.com/photos/213780/pexels-photo-213780.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
title: Naruto
}]
]
所以它是一个具有属性的数组的数组。这是因为您有每个查询的结果列表。
要从上述结构中获取数据,您可以执行以下操作:
child: Text(filterMangaList[index][0]["title"]),
但这只会显示每个查询的第一个结果,这可能不是您想要的。
要查看所有查询的所有结果,您必须将它们添加到平面列表而不是嵌套列表中。一个简单的方法是:
filterMangaList.addAll(filterManga);
完成此更改后,您的 filterMangaList
包含所有查询的所有结果的平面列表,然后您可以使用原始代码将其显示在 ListView
中。
关于flutter - 如何从 Flutter 中的列表中提取 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73592411/