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

问题描述

我是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
  );
}

,

我认为您在添加元素之前就在访问它,因为它是async方法。
试试这个

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"]); 
   });
}

希望它能起作用!