gpt4 book ai didi

flutter - 完成迭代循环后 map 为空

转载 作者:行者123 更新时间:2023-12-03 04:20:21 28 4
gpt4 key购买 nike

我只需要在完成迭代循环后打印 map 的键数。

 import 'dart:collection';
import 'dart:convert';
import 'dart:ffi';
import 'package:flutter/services.dart';
import 'package:flutter_sample/model/GazStation.dart';
import 'package:flutter_sample/util/util.dart';
import 'package:geolocator/geolocator.dart';
import 'package:logger/logger.dart';

Future<GazStation> getNearestGazStation() async {
List<GazStation> gazStationList = await getGazStationList();
Position myPosition = await Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
Map<double, GazStation> map = new HashMap();
gazStationList.forEach((gazStation) {
_getDistanceMetersToGazStation(myPosition, gazStation).then((distanceInMeters) {
_logger.d("put_key = ${distanceInMeters}");
map.putIfAbsent(distanceInMeters, () => gazStation);
});
});
_logger.d("map_keys_count = ${map.keys.length}");
return null;
}

Future<double> _getDistanceMetersToGazStation(Position myPosition, GazStation gazStation) async {
var distance = Geolocator().distanceBetween(
myPosition.latitude,
double.parse(gazStation.Latitude),
myPosition.longitude,
double.parse(gazStation.Longitude));
return distance;
}
但是在日志中首先打印:
 map_keys_count = 0
并多次打印后
put_key = xxx

最佳答案

要正确填写 map ,您必须 await你的 future 。但是,填充 map 然后返回 null 可能不是该方法应该做的。这看起来更像是您正在寻找的东西:

Future<GazStation> getNearestGazStation() async {
final gazStationList = await getGazStationList();
final myPosition = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);

GazStation closest = null;
double closestDistance = double.maxFinite;

for(var gazStation in gazStationList) {
final distanceInMeters = await _getDistanceMetersToGazStation(myPosition, gazStation);

if(distanceInMeters < closestDistance) {
closestDistance = distanceInMeters;
closest = gazStation;
}
}

return closest;
}

关于flutter - 完成迭代循环后 map 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63017391/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com