import 'package:cloud_firestore/cloud_firestore.dart';
Future<double> getTotalSyrupPrice() async {
// Get a reference to the syrup document
DocumentReference syrupRef = FirebaseFirestore.instance
.collection('your_collection') // Replace with your collection name
.doc('syrup_document_id'); // Replace with the ID of the syrup document
// Get all the ingredients subcollection documents of the syrup
QuerySnapshot ingredientsSnapshot = await syrupRef
.collection('ingredients') // Replace with your subcollection name
.get();
double totalPrice = 0;
// Iterate over the ingredient documents and sum up the price values
for (DocumentSnapshot ingredientDoc in ingredientsSnapshot.docs) {
Map<String, dynamic>? ingredientData = ingredientDoc.data();
if (ingredientData != null && ingredientData.containsKey('price')) {
totalPrice += ingredientData['price'];
}
}
return totalPrice;
}
1条答案
按热度按时间yyhrrdl81#
要从Firebase中的另一个文档的子文档中获取字段值的总和,可以在代码中组合使用Firestore查询和数据操作。下面是一个使用Flutter和cloud_firestore包实现此功能的示例:
在上面的示例中,将'your_collection'替换为您的集合的名称,将'syrup_document_id'替换为您想要从中检索成分的糖浆文档的ID。另外,请确保将“配料”替换为存储配料的子集合的名称。
getTotalSyrupPrice函数执行查询以获取糖浆文档的子集合中的所有成分文档。然后,它遍历成分文档并对价格值求和。最后,返回总价。
只要需要检索糖浆成分的总价,就可以调用getTotalSyrupPrice函数。记住处理任何潜在的错误并等待函数,因为它返回Future。