Flutter - 循环访问来自rest api的纬度和经度列表以获取两个坐标之间的距离

2024-03-12

在我的代码中,能够成功获取两个坐标(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())

],),

))



我在您的代码中看到了多个错误。

首先,你的代码无法编译

  • DoubleDart 语言中 type 为小写。
  • 你不应该初始化double带有空的变量String.

其次,您将全局状态与异步调用结合使用。如果您只是将参数传递给 getDistance 方法,那就更好了。像这样:

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

  return distanceInMeters / 1000;
}

最后你应该使用未来建造者 https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html打电话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)],
          ),
        );
     });
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Flutter - 循环访问来自rest api的纬度和经度列表以获取两个坐标之间的距离 的相关文章

随机推荐