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

本秂侑毒 提交于 2020-04-07 08:39:50

问题


In my code being able to successfully get the distance between the two coordinate (lAT and LNG) but my listview returns the value for only one of the list of values. Kindly find my code below.

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())

],),

))



回答1:


I have seen multiple mistake in your code.

First, your code is not compiling

  • Double type is lowercase in Dart language.
  • You should not initialize a double variable with an empty String.

Second, you use global states with async calls. It would be better, if you just pass parameters into getDistance method. Like this:

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

  return distanceInMeters / 1000;
}

Finally you should use a FutureBuilder to call 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)],
          ),
        );
     });
});


来源:https://stackoverflow.com/questions/60994455/flutter-looping-through-a-list-of-latitude-and-longitude-from-rest-api-to-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!