[英]Read subcollection from Firestore flutter
如何從 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");
// });
}
Model class
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
};
}
}
有人可以通過我的一些光線。 我想將該子集合讀入列表。 我正在使用 cloud_firestore:^0.12.9+4。
你只想
Firestore.collection("collection/documentid/subcollectionname').getdocuments
這種行為有很多原因。 一種可能是您查詢不存在的文檔。
考慮到這一點,也許嘗試使用此代碼段將解決您的問題:
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);
});
});
讓我知道這是否有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.