使用geoflutterfire2获取中心点距离时遇字段不存在错误
解决geoflutterfire2获取distance字段报错的问题
- 核心原因:未在查询链中调用
withDistance()方法,Firestore不会自动返回distance字段,直接读取必然提示字段不存在。 - 正确写法示例:
// 初始化中心点 final center = GeoFirePoint(latitude, longitude); // 构建带distance返回的地理查询 final collectionRef = FirebaseFirestore.instance.collection('target_collection'); final geoQuery = geo.collection(collectionRef: collectionRef) .within( center: center, radius: 5, // 搜索半径(单位:公里) field: 'geo_position', // 文档中存储GeoFirePoint的字段名 strictMode: true, ) .withDistance(); // 关键:必须调用此方法才会返回distance字段 // 监听查询结果 geoQuery.listen((docs) { for (var doc in docs) { final distance = doc.data()?['distance']; if (distance != null) { print('当前文档与中心点距离:${distance}km'); } } }); - 注意事项:
- 确认文档中存储的是
GeoFirePoint类型数据,且字段名与within方法的field参数完全匹配。 - geoflutterfire2与老版GeoFlutterFire用法差异:老版本可能默认返回distance,而geoflutterfire2需要显式调用
withDistance()启用该字段返回。 - 若使用
get()获取单次查询结果,同样需在查询链末尾添加withDistance(),再从返回的docs列表中读取每个文档的distance字段。
- 确认文档中存储的是
内容的提问来源于stack exchange,提问作者DeKekem
相关产品推荐
相关产品推荐

