Flutter中Firestore数据查询异常:返回空列表求助
Firestore查询返回空列表的问题解决
问题根源:数据存储路径与查询路径不匹配
你的数据实际存储在多层嵌套的深层路径中,但查询仅到了中间层级,自然无法获取到数据。修正数据创建路径(简化逻辑)
原代码中res.doc(res.id)是错误用法:res是hotels集合,res.id返回的是集合名称"hotels",这会创建hotels/hotels这个无意义的文档。同时嵌套层级过于冗余,建议简化路径:// 简化后路径:hotels/{email}/{hotelName}/hotel_details var hotelsRef = FirebaseFirestore.instance.collection("hotels"); var response = await hotelsRef .collection(data.email) .doc(data.hotelName) .collection('hotel_details') .add({ 'hotel_name': data.hotelName, 'hotel_email': data.email, });若不需要多层嵌套,也可以直接将数据存在
hotels集合下:var response = await FirebaseFirestore.instance.collection("hotels").add({ 'hotel_name': data.hotelName, 'hotel_email': data.email, });匹配路径调整查询代码
如果使用第一种简化路径,查询代码需对应调整:final hotelsRef = FirebaseFirestore.instance.collection("hotels"); // 先确认酒店文档存在,再查询其下的hotel_details集合 final hotelDoc = await hotelsRef.collection(email).doc(hotelName).get(); if (hotelDoc.exists) { final response = await hotelsRef.collection(email).doc(hotelName).collection('hotel_details').get(); // 处理返回的response.docs }若选择直接存在
hotels集合,可通过条件查询:final response = await FirebaseFirestore.instance.collection("hotels") .where('hotel_email', isEqualTo: email) .get();额外检查项
- 确认Firestore安全规则允许读取目标路径的数据,避免权限限制导致空结果。
- 核对查询时的
email变量值与创建数据时的data.email完全一致(注意大小写、空格等细节)。 - 登录Firebase控制台查看数据实际存储路径,验证是否与预期一致。
内容的提问来源于stack exchange,提问作者Binod Bhandari
相关产品推荐
相关产品推荐

