簡體   English   中英

Flutter - 從 rest api 循環遍歷緯度和經度列表以獲取兩個坐標之間的距離

[英]Flutter - Looping through a list of latitude and longitude from rest api to get distance between two coordinates

在我的代碼中,能夠成功獲得兩個坐標(lAT 和 LNG)之間的距離,但我的列表視圖僅返回值列表之一的值。 請在下面找到我的代碼。

String lat = "";
String lng = "";
Double distanceInKilometers = "";

Future getDistance() async {

    distanceInMeters = await Geolocator().distanceBetween(
        currentLocation.latitude, currentLocation.longitude, double.parse(lat), double.parse(lng));

    distanceInKilometers = distanceInMeters.toInt() / 1000;

    }


ListView.separated( itemCount: content.length,
                     itemBuilder: (context, position) {
                                      lat = content[position].lat;
                                      lng = content[position].lng;

                      return Container(
child: Column(
children: <Widget>[
new Text(distanceInKilometers.toString())

],),

))


我在您的代碼中看到了多個錯誤。

首先,你的代碼沒有編譯

  • Double類型在 Dart 語言中是小寫的。
  • 不應使用空String初始化double變量。

其次,您將全局狀態與異步調用一起使用。 如果您只是將參數傳遞給 getDistance 方法會更好。 像這樣:

Future<double> getDistance(double lat, double long) async {
  final distanceInMeters = await Geolocator().distanceBetween(
        currentLocation.latitude,
        currentLocation.longitude,
        lat,
        lng
  );

  return distanceInMeters / 1000;
}

最后,您應該使用FutureBuilder來調用getDistance

ListView.separated(
  itemCount: content.length,
  separatorBuilder: (context, position) {
   // return a separator widget;
  },
  itemBuilder: (context, position) {
    final current = content[position];
    return FutureBuilder<String>(
      future: getDistance(current.lat, current.long)
                   .then((value) => value.toString()),
      builder: (context, snapshot) {
        return Container(
          child: Column(
            children: <Widget>[new Text(snapshot.data)],
          ),
        );
     });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM