本文介绍了完成迭代循环后,映射为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要在完成迭代循环后再打印地图的键计数即可。

I need only after finish iterate loop then print map's key count.

 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


推荐答案

要正确填写地图,您必须正确地等待。但是,填充地图然后无论如何都返回null可能不是此方法应该做的。看起来更像是您要寻找的东西:

To fill you map correctly, you have to await your futures properly. However, filling a map and then returning null anyway is probably not what this method should do. This looks more like it could be what you are looking for:

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;
  }

这篇关于完成迭代循环后,映射为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 18:52