阅读来自Firestore Flutter的子集合

时间:2019-10-05 12:05:07

标签: list flutter collections google-cloud-firestore

如何从Flutter Firestore中读取子集合。我正在使用cloud_firestore。我已成功将数据添加到Firestore中,但无法检索(尝试并失败)。

    FirebaseUser user=await _firebaseAuth.currentUser();
    uid=user.uid;
    return user.uid;
  }
  Future addSpend(Spend spend) {
    String date=DateFormat('MM-yyyy').format(spend.date);
    print("BLB DB $date");
    return Firestore.instance.runTransaction((Transaction transactionHandler) {
      return Firestore.instance
          .collection("Spends")
          .document(uid).collection(date).document()
          .setData(spend.toJson());
    });
  }

我试图将所有这些子集合读入对象列表。但是失败了。

//    QuerySnapshot querySnapshot = await Firestore.instance.collection("Spends").document(Repository.uid).collection("10-2019").getDocuments();
//    print("BLB ${querySnapshot.documentChanges}");
//    var list = querySnapshot.documents;
//    return list;


//   List<DocumentSnapshot> templist;
//   List<Map<dynamic, dynamic>> list = new List();
//    var path=Firestore.instance.collection("Spends").document(uid).collection("10-2019");
//
//    var collectionSnapshot=await path.getDocuments();
//    print("BLB collection ${collectionSnapshot}");
//   templist = collectionSnapshot.documents;
//   print("BLB templist ${templist.length}");
//   list = templist.map((DocumentSnapshot docSnapshot){
//     return docSnapshot.data;
//   }).toList();
//
//   return list;
   var doc = await Firestore.instance.collection('Spends').reference();
   doc.getDocuments().then((res){
     print("BLB DB ${res.documentChanges.length}");
   }).catchError((e){
     print("BLB DB error $e");
   });

//   doc.then((document){
//     print("BLB DB ${document.exists}");
//   }).catchError((e){
//     print("BLB DB error $e");
//   });
  }

模型类

  Spend();
  String id,amount; String title; String category; DateTime date; String description;

  Spend.fromSnapshot(DocumentSnapshot snapshot)
      : id = snapshot.documentID,
        amount = snapshot['amount'],
        category = snapshot['category'],
        date = snapshot['date'],
        title = snapshot['title'],
        description = snapshot['description'];

  toJson(){
    return {
      "amount":amount,
      "category":category,
      "date":date,
      "description":description,
      "title":title

    };
  }
}

Firebase database Firebase DB conti..

有人可以照亮我吗?我想将该子集合读入列表。我正在使用cloud_firestore:^ 0.12.9 + 4。

2 个答案:

答案 0 :(得分:2)

此行为有很多原因。一个人可能就是你query for documents that don’t exist

还要考虑Firestore documentation for Listing subcollections of a document

考虑到这一点,也许尝试使用此代码片段即可解决您的问题:

var spendsRef = await Firestore.instance.document('Spends/YOUR_DOCUMENT_ID');
spendsRed.getCollections() => then(collections => {
    collections.forEach(collection => {
    console.log('Found subcollection with id:', collection_id);
 });
});

让我知道这是否有帮助。

答案 1 :(得分:1)

您只想

Firestore.collection("collection/documentid/subcollectionname').getdocuments