[英]How to get list of document from firestore in flutter based on field value
[英]Flutter Firestore - How to get data from a Document Reference in a Document Field?
我正在构建一个具有不同问题类型的自学应用程序。 现在,其中一个问题有一个包含 DocumentReferences 列表的字段:
在 Flutter 中,我有以下代码:
Query<Map<String, dynamic>> questionsRef = firestore
.collection('questions')
.where('lesson_id', isEqualTo: lessonId);
await questionsRef.get().then((snapshot) {
snapshot.docs.forEach((document) {
var questionTemp;
switch (document.data()['question_type']) {
....
case 'cards':
questionTemp = CardsQuestionModel.fromJson(document.data());
break;
....
}
questionTemp.id = document.id;
questions.add(questionTemp);
});
});
现在,使用“questionTemp”我可以访问所有字段(lesson_id、options、question_type 等),但是当涉及到“cards”字段时,我如何访问该文档引用中的数据?
有没有办法告诉 firestore.instance 自动从这些引用中获取数据? 或者我需要为每个人打一个新电话吗? 如果是这样,我该怎么做?
提前感谢您的支持!
有没有办法告诉 firestore.instance 自动从这些引用中获取数据? 或者我需要为每个人打一个新电话吗?
不,没有任何方法可以自动获取这些文档。 您需要为每个数组元素构建相应的DocumentReference
并获取文档。
要构建参考,请使用doc()
方法
DocumentReference docRef = FirebaseFirestore.instance.doc("cards/WzU...");
然后在此DocumentReference
上使用get()
方法。
docRef
.get()
.then((DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
print('Document exists on the database');
}
});
具体来说,您可以遍历cards
并将get()
方法返回的所有期货传递给“等待多个期货完成并收集其结果”的wait()
方法。 有关更多详细信息,请参阅此SO 答案,并注意“返回的未来值将是按照迭代期货提供期货的顺序生成的所有值的列表。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.