Flutter-从rest api遍历经纬度列表以获取两个坐标之间的距离 [英] Flutter - Looping through a list of latitude and longitude from rest api to get distance between two coordinates
本文介绍了Flutter-从rest api遍历经纬度列表以获取两个坐标之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的代码中,能够成功获取两个坐标(lAT和LNG)之间的距离,但是我的listview仅返回值列表之一的值.请在下面找到我的代码.
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())
],),
))
推荐答案
我在您的代码中发现了多个错误.
I have seen multiple mistake in your code.
首先,您的代码未编译
-
Double
类型在Dart语言中为小写字母. - 您不应使用空的
String
初始化double
变量.
Double
type is lowercase in Dart language.- You should not initialize a
double
variable with an emptyString
.
第二,将全局状态与异步调用一起使用.如果只将参数传递给getDistance方法,那会更好.像这样:
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;
}
最后,您应该使用 FutureBuilder 来调用getDistance
:
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)],
),
);
});
});
这篇关于Flutter-从rest api遍历经纬度列表以获取两个坐标之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文