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

前端 未结 1 487
灰色年华
灰色年华 2021-01-27 10:05

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 fi

相关标签:
1条回答
  • 2021-01-27 10:18

    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)],
              ),
            );
         });
    });
    
    0 讨论(0)
提交回复
热议问题