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

如何按'spot_distancia'键对更新后的文档集合进行排序?

解决方法

你当前的代码存在一个问题:每次循环都会用当前遍历的文档数据覆盖datosSpots变量,最后只会保留最后一个文档的内容。要实现排序,得先把所有处理好的文档数据存储到一个列表中,再对列表进行排序。

具体修改步骤如下:

  1. 先定义一个列表,用来保存所有处理后的文档数据:
List<Map<String, dynamic>> processedSpots = [];
  1. 遍历文档集合时,处理每个文档的数据并添加到列表:
value.docs.forEach((spot) {
  // 复制文档数据,避免直接引用原文档的可变数据(可选,根据业务需求调整)
  Map<String, dynamic> datosSpots = Map.from(spot.data() as Map<String,dynamic>);

  GeoPoint spotLocation = datosSpots['location'];
  double latSpot = spotLocation.latitude;
  double lonSpot = spotLocation.longitude;

  // 计算距离
  double distancia = calculateDistance(
      widget.latitud, widget.longitud, latSpot, lonSpot);
  
  // 若"spot_distancia"键可能不存在,用putIfAbsent避免报错;确定存在的话可以用update
  datosSpots.putIfAbsent("spot_distancia", () => distancia);
  
  // 将处理完成的Map加入列表
  processedSpots.add(datosSpots);
  print("distancia cambiada ${datosSpots['spot_distancia']}");
});
  1. 对列表按spot_distancia字段排序:
// 升序排序(从近到远)
processedSpots.sort((a, b) => a['spot_distancia'].compareTo(b['spot_distancia']));

// 如需降序(从远到近),反转比较逻辑即可:
// processedSpots.sort((a, b) => b['spot_distancia'].compareTo(a['spot_distancia']));

处理完成后,processedSpots就是按距离排序好的文档集合。

内容的提问来源于stack exchange,提问作者mvasco

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:25:44