loops - 将对象列表与地图 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;});
但显然这只会为每个工具添加第一次距离测量。
有什么方法可以遍历每个工具,然后添加距离矩阵图的距离?每个距离将与列表中的每个工具按顺序排列。
解决方案
我想这就是你想做的
finalResults.forEach((tool) {
distanceMatrix.elements.forEach((element){
tool.toolLocation = element.distance.text;
});
});
If elements
is also a List
then 你可以使用foreach
语法来遍历它。
推荐阅读
- node.js - 使用匹配的相邻字段查找文档
- spring - Spring 5 中的 Log4jConfigurer
- sql - 如何在 SQL 查询中按当前值和先前值对两行进行排序?
- java - @ConfigurationProperties 不绑定属性
- ruby-on-rails - Bootstrap 5 下拉菜单的 Rails 6 问题
- python - 如何将 'Apr 21, 2021, 7:43:51 AM GMT+5:30' 解析为时间戳?
- java - Jackson 反序列化的不稳定行为:“未分配 _valueDeserializer”
- azure-data-explorer - 当变量在作用域内时,它仍然不引用任何已知的列、表、变量或函数
- python - 熊猫:有条件地添加月份和日期
- python - Python:接收变量名作为输入,存储在另一个文件中