You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 00:07:04