Flutter中Firestore DocumentReference字段查询无结果问题排查
问题描述
我有一个items集合,其中的文档包含category字段,类型为DocumentReference。我需要查询所有category字段与指定引用匹配的文档,但当前编写的查询代码返回空结果;移除where条件后则能正常显示所有带分类引用的数据。
查询代码
finalReference({String? reference}) { String reference ='categories/${widget.firstDocs}/FirstCategories/$secondKey/SecondCategories/${snapData[index].id}' return FirebaseFirestore.instance .collection('items').where('category',isEqualTo: reference) .snapshots(); }
打印的category字段内容
DocumentReference<Map<String, dynamic>>(categories/7gGcmhHZBu7UbnrpPAov/FirstCategories/TyFolH2B1j0b8AUz55ZA/SecondCategories/vIeGUNBHZcNudEwMirQY)
数据展示代码
StreamBuilder<QuerySnapshot<Map<String, dynamic>>>( stream: CallData().finalReference(reference: widget.finalReference), builder: (context, snapshot) { if (snapshot.hasError) { return Center(child: Text('snapshot Error:${snapshot.error}')); } if (snapshot.hasData) { var snapData = snapshot.data!.docs; if (kDebugMode) { print(snapData.length); } return ListView.builder( itemCount: snapData.length, itemBuilder: (context, index) { if (kDebugMode) { print('items is ${snapData[index].get('title')}'); print('items is ${snapData[index].get('category')}'); } return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ CategoryCard( hasIcon: false, mTitle: '${snapData[index].get('title')}', mSubTitle: '${snapData[index].get('category')}', ), const Divider(), ], ); }); } return const Center(child: CircularProgressIndicator()); }, )
问题原因与解决方法
问题核心是类型不匹配:你用字符串类型的文档路径去匹配DocumentReference类型的字段,Firestore不会自动将字符串转换为引用对象,因此无法匹配到目标文档。
修改方案:
- 将传入的字符串路径转换为
DocumentReference对象,再用于查询匹配。 - 修复原代码中变量重定义的问题(参数与内部变量同名)。
修改后的查询代码:
Stream<QuerySnapshot<Map<String, dynamic>>> finalReference({String? referencePath}) { // 将字符串路径转为DocumentReference对象 final categoryRef = FirebaseFirestore.instance.doc(referencePath!); return FirebaseFirestore.instance .collection('items') .where('category', isEqualTo: categoryRef) .snapshots(); }
额外注意:确保传入的referencePath是完整且格式正确的文档路径,与打印的category引用路径完全一致。
内容的提问来源于stack exchange,提问作者Saied Rahimi
相关产品推荐
相关产品推荐

