gpt4 book ai didi

flutter - 从Flutter中的Firestore检索数据后为空列表

转载 作者:行者123 更新时间:2023-12-03 04:39:25 25 4
gpt4 key购买 nike

我是Flutter的新手,所以对不起,这个问题似乎微不足道或无关紧要!
当我使用Cloud Firestore时,我创建了另一个用于获取和设置数据的类Repository,我要针对此特定问题的数据存储在集合中,因此我将集合中的所有文档作为QuerySnapshot获得,然后添加所有以List<DocumentSnapshot>的文档。
这是方法:

Future<List<DocumentSnapshot>> getCollection(CollectionReference colRef) async {
List<DocumentSnapshot> dummyList = new List();
await colRef.getDocuments().then((value) {
dummyList.addAll(value.documents);
});
return dummyList;
}
存储库:
CollectionReference memoriesColRef =
_firestore
.collection("username")
.document("memories")
.collection("allMem");

List<DocumentSnapshot> documentList = new List();
await getCollection(memoriesColRef).then((value) {
documentList.addAll(value);
});
完成所有这些之后,我在UI类中设置了一个方法来调用此 Repository,并且当我在 build函数中调用该方法时,该方法可以正常工作,因为我已经传递了用于访问数据的全局列表,在其中添加值
UI类
build(...) {
getMemories().then((value) {
print("value size: " + value.length.toString()); // 1
memoriesListMap.addAll(value); // global variable
});
print("valSize: " + memoriesListMap.length.toString()); // 0
print("val: " + memoriesListMap[0]["title"]); // error line
}

Future<List<Map<String, dynamic>>> getMemories() async{
List<Map<String, dynamic>> dummyListMap = new List();

await MemoryOper().getMemories().then((value) {
print("memVal: " + value[0]["title"]); // appropriate value
dummyListMap.addAll(value);
});
return dummyListMap;
}
错误 RangeError (index): Invalid value: Valid value range is empty: 0 \
我不知道是什么原因造成的,但是请帮帮我!谢谢
编辑:
ListView.builder(
itemBuilder: (BuildContext context, int index) {
String title = memoriesListMap[index]["title"]; // error prone line
int remind = memoriesListMap[index]["remind"];
String link = memoriesListMap[index]["link"];

最佳答案

除了nvoigt所说的之外,此article将帮助您了解如何实现Future Builder,在您的特定情况下,您可以执行以下操作:

build(...){
..
body: getMemories(),
..
}

Widget getMemories() {
return FutureBuilder(
builder: (context, projectSnap) {
if (projectSnap.connectionState == ConnectionState.none &&
projectSnap.hasData == null) {
return Container();
}
return ListView.builder(
itemCount: projectSnap.data.length,
itemBuilder: (context, index) {
ProjectModel project = projectSnap.data[index];
return Column(
children: <Widget>[
// Widget to display the list of project
],
);
},
);
},
future: getCollection(), //this is the important part where you get the data from your Future
);
}

关于flutter - 从Flutter中的Firestore检索数据后为空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63509535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com