我的目标是对与用户地理位置相比的机架列表进行排序。这是我的代码:
constructor(props)
问题出在for循环中,变量import 'package:geolocator/geolocator.dart';
import 'rack.dart';
import 'dart:async';
class RackList {
List<Rack> _racks;
RackList(this._racks);
get racks => _racks;
factory RackList.fromJson(Map<String,dynamic> json){
var list = json['racks'] as List;
Future<int> calculateDistance(var element) async{
var startLatitude=45.532;
var startLongitude=9.12246;
var endLatitude=element.latitude;
var endLongitude=element.longitude;
var dist = await Geolocator().distanceBetween(
startLatitude,
startLongitude,
endLatitude,
endLongitude);
var distance=(dist/1000).round();
return distance;
}
list = list.map((i) => Rack.fromJson(i)).toList();
for (int i = 0; i < list.length; i++) {
var dist = calculateDistance(list[i]);
print(dist); //prints Instance of 'Future<int>'
list[i].distance=dist; //crash
}
list.sort((a, b) => a.distance.compareTo(b.distance));
return RackList(list);
}
}
是dist
类型,不能分配给Future<int>
。如何将该值转换为普通的int?
我已经尝试过@Nuts的解决方案,但是:
list[i].distance
就像在周期外,我丢失了var distances = new List();
for (int i = 0; i < list.length; i++) {
calculateDistance(list[i]).then((dist) {
distances.add(dist);
print(distances[i]); //print the correct distance
});
}
print("index 0 "+distances[0].toString()); //prints nothing
列表中的所有值
答案 0 :(得分:0)
import 'package:geolocator/geolocator.dart';
import 'rack.dart';
import 'dart:async';
class RackList {
List<Rack> _racks;
RackList(this._racks);
get racks => _racks;
factory RackList.fromJson(Map<String,dynamic> json){
var list = json['racks'] as List;
calculateDistance(var element) async{
var startLatitude=45.532;
var startLongitude=9.12246;
var endLatitude=element.latitude;
var endLongitude=element.longitude;
var dist = await Geolocator().distanceBetween(
startLatitude,
startLongitude,
endLatitude,
endLongitude);
int distance=(dist/1000).round();
return distance;
}
list = list.map((i) => Rack.fromJson(i)).toList();
for (int i = 0; i < list.length; i++) {
calculateDistance(list[i]).then((dist){
print("${dist}"); //prints Instance of 'Future<int>'
list[i].distance=dist; //crash
});
}
list.sort((a, b) => a.distance.compareTo(b.distance));
return RackList(list);
}
}
答案 1 :(得分:0)
还可以:
var dist = await calculateDistance(list[i]);
它将等待Future返回int值。
另一个解决方案是:
calculateDistance(list[i]).then((dist) {list[i].distance=dist;})
Future完成后,运行功能。