我已经创建了一个带有嵌套集合的FireStore,现在我想根据某些条件从它中获取数据。我试图创建一个“未来”,尝试从集合中获取数据并将其存储在其中,然后将其返回到"FutureBuilder“中。但出于某种原因,我的代码正在工作,但它没有显示任何输出。
我的数据库结构
Class
Documents
---------------
course (collection)
Documents
CourseName
Slot
TeacherId
---------------
ClassId
ClassName从集合中获取数据的代码
Future<List<Teaching>> findTeachingCourses(String documnentId) async {
Future<List<Teaching>> teachingList = Future<List<Teaching>>.delayed(
Duration(seconds: 0),
() {
Future<QuerySnapshot> result = classCollection.getDocuments();
List<Teaching> list = new List<Teaching>();
result.then(
(value) => value.documents.forEach(
(element) {
Future<QuerySnapshot> result2 = classCollection
.document(element.documentID)
.collection("course")
.getDocuments();
result2.then(
(value2) => value2.documents.forEach(
(element2) {
//print(element.data);
//print(element2.data);
Stream<DocumentSnapshot> result3 =
collection.document(documnentId).get().asStream();
result3.forEach((element3) {
if (element3.data["id"] == element2.data["teacherId"]) {
Courses course = Courses(element2.data["courseName"],
element2.data["slot"], element2.data["teacherId"]);
Teaching teaching =
Teaching(course, element.data["classid"]);
list.add(teaching);
print(course.toJson());
print(element3.data["id"]);
}
});
},
),
);
},
),
);
return list;
},
);
return teachingList;
}生成器代码
child: FutureBuilder<List<Teaching>>(
future: repository.findTeachingCourses(_CurrentUser.documentId),
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
//return showLoaderDialog(context);
print("show loading dialog");
}
List<Teaching> list = snapshot.data ?? [];
return ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
Teaching teaching = list[index];
return Card(
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
children: <Widget>[
Text("Class ID : " + teaching.classid.toString()),
Text("Course : " + teaching.course.courseName),
],
),
),
);
},
);
},
),代码正在运行,没有给出任何错误,但我没有得到任何输出。有什么建议吗?
发布于 2021-01-02 06:23:55
这根本不是一个完整的解决方案,但希望能让您了解如何组织代码。
基本上,您可以使用等待,而不是然后删除您的代码被包装成多层括号。您还应该考虑给变量更有意义的名称!
下面是我重写您的代码的尝试,但是在发现我不知道代码中collection变量是什么之后,我没有完成它。
Future<List<Teaching>> findTeachingCourses(String documnentId) async {
// This would be result
final QuerySnapshot classesSnapshot = await classCollection.get();
// This would be result2 combined in a single List
final List<Future<QuerySnapshot>> coursesFuture = classesSnapshot.docs
.map((classDoc) =>
classCollection.doc(classDoc.id).collection("course").get())
.toList();
// This would be element2 combined in a single List
final List<QuerySnapshot> coursesSnapshotList =
await Future.wait(coursesFuture);
// This would be element3
final DocumentSnapshot targetSnapshot =
await classCollection.doc(documnentId).get();
}https://stackoverflow.com/questions/65534996
复制相似问题