我目前有一个应用程序可以显示 1.5 公里半径内附近的医院,它看起来像这样:
我遇到的问题是我无法弄清楚如何根据从最低到最高的计算距离对卡片进行排序。
我做了一个List<double> doubleList = [];
存储计算距离的列表并使用 doubleList.sort();
对其进行排序.
这是代码片段:
return new ListView.builder(
shrinkWrap: true,
itemCount: jsonresponse.length,
itemBuilder: (context, index){
String name = jsonresponse[index]["Name"];
String lat = jsonresponse[index]["Latitude"];
String lng = jsonresponse[index]["Longitude"];
var distance = new GreatCircleDistance.fromDegrees(latitude1: double.parse(widget.lat), longitude1: double.parse(widget.lng), latitude2: double.parse(lat), longitude2: double.parse(lng));
var totaldistance = distance.haversineDistance().toStringAsFixed(2);
double distanceDouble = double.parse(totaldistance);
if(distanceDouble < 1500.00){
doubleList.add(distanceDouble);
doubleList.sort((a, b){
return a.compareTo(b);
});
print(doubleList);
return new Column(
children: <Widget>[
new Card(
child: new ListTile(
title: new Text(name),
subtitle: new Text("$distanceDouble m away"),
trailing: new IconButton(
icon: new Icon(Icons.info),
onPressed: (){
makeDialog(lat, lng);
}),
),
)
],
);
}else{
return new Container();
}
});
这是打印时排序后的距离值的输出:
I/flutter ( 4286): [987.8]
I/flutter ( 4286): [987.8, 1014.87]
I/flutter ( 4286): [987.8, 1014.87, 1352.22]
I/flutter ( 4286): [128.26, 987.8, 1014.87, 1352.22]
I/flutter ( 4286): [128.26, 987.8, 1014.87, 1260.73, 1352.22]
I/flutter ( 4286): [122.91, 128.26, 987.8, 1014.87, 1260.73, 1352.22]
I/flutter ( 4286): [122.91, 128.26, 987.8, 1014.87, 1260.73, 1303.36, 1352.22]
I/flutter ( 4286): [122.91, 128.26, 987.8, 1014.87, 1232.47, 1260.73, 1303.36, 1352.22]
I/flutter ( 4286): [122.91, 128.26, 987.8, 1014.87, 1232.47, 1232.47, 1260.73, 1303.36, 1352.22]
我的问题是:
如何确保小部件将遵循已排序距离值的顺序?
最佳答案
ListView.builder
正在使用一个 itemBuilder 来负责构建一个项目。在这里要小心,每次构建项目时都要进行排序。
您需要在调用 List.builder
之前对您的 jsonresponse
进行排序,否则 jsonresponse[index]
将不正确。
关于dart - flutter : Sort widget according to a sorted list of values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52422124/