如何对所有折扣集合求和,然后得到另一个集合中所有学生的这些值的总和



当我测试这段代码以获取allDiscountForAllStudents的列表时,我得到了一个空列表。为什么呢?

这是代码

getAllDiscountForAllStudents() async {
int _allDiscountForAllStudents = 0;
QuerySnapshot querySnapshot = await FirebaseFirestore.instance
.collection('courses')
.doc(_id2)
.collection('course_students')
.where('withdraw', isEqualTo: false)
.get();
List allCourseStudents = querySnapshot.docs.toList();
QuerySnapshot snapshot2;
for (int i = 0; i < allCourseStudents.length; i++) {
snapshot2 = await FirebaseFirestore.instance
.collection('discounts')
.where('Course Id', isEqualTo: _id2)
.where('User Id', isEqualTo: allCourseStudents[i]['ID'])
.where('Approved', isEqualTo: true)
.get();
}
List allDiscountForAllStudents = snapshot2.docs.toList();
print(allDiscountForAllStudents);
return _allDiscountForAllStudents;
}

看起来您用最后获得的学生的数据覆盖了总列表,如果该列表没有数据,则将为空。你可以试试下面的代码吗:

getAllDiscountForAllStudents() async {
int _allDiscountForAllStudents = 0;
QuerySnapshot querySnapshot = await FirebaseFirestore.instance
.collection('courses')
.doc(_id2)
.collection('course_students')
.where('withdraw', isEqualTo: false)
.get();
List allCourseStudents = querySnapshot.docs.toList();

List allDiscountForAllStudents=[];
for (int i = 0; i < allCourseStudents.length; i++) {
QuerySnapshot snapshot2;
snapshot2 = await FirebaseFirestore.instance
.collection('discounts')
.where('Course Id', isEqualTo: _id2)
.where('User Id', isEqualTo: allCourseStudents[i]['ID'])
.where('Approved', isEqualTo: true)
.get();
allDiscountForAllStudents.addAll(snapshot2.docs.toList());
}

print(allDiscountForAllStudents);
return _allDiscountForAllStudents;
}

最新更新