首页 > 解决方案 > 将对象列表与地图 Dart 中的信息相结合

问题描述

我正在尝试将通过 http 调用收到的地图中的信息添加到 Dart 中的对象列表中。例如,对象列表是具有 toollocation 属性的工具:

Tool(
      {this.make,
      this.model,
      this.description,
      this.tooltype,
      this.toollocation,
      this.paymenttype,
      this.userid});

我还使用谷歌距离矩阵 api 来收集该工具与用户的距离。

Future<DistanceMatrix> fetchDistances() async {
    await getlocation();
    latlongdetails = position['latitude'].toString() +
        ',' +
        position['longitude'].toString();
    print(latlongdetails);
    print('still running');
    final apiresponsepc = await http
        .get(
            'https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=$latlongdetails&destinations=$postcodes&key=xxx');
    distanceMatrix =
        new DistanceMatrix.fromJson(json.decode(apiresponsepc.body));
    return distanceMatrix;
  }

我过去一直在做的是调用未来,并在我返回该工具的原始结果后获得距离。但是我希望能够按距离对工具结果进行排序,因此我需要遍历列表中的每个工具并为每个工具添加距离。

到目前为止,我一直在工具列表上尝试 foreach 循环:

finalresults.forEach((tool){ tool.toollocation = distanceMatrix.elements[0].distance.text;});

但显然这只会为每个工具添加第一次距离测量。

有什么方法可以遍历每个工具,然后添加距离矩阵图的距离?每个距离将与列表中的每个工具按顺序排列。

标签: loopsforeachdartflutter

解决方案


我想这就是你想做的

finalResults.forEach((tool) {
  distanceMatrix.elements.forEach((element){
    tool.toolLocation = element.distance.text;
  });
});

If elementsis also a Listthen 你可以使用foreach语法来遍历它。


推荐阅读