我正在实现一个ListView,该视图将显示一张卡片,其中包含用户与每个卡片位置之间的距离,该卡片的位置是从Firestore获取的。我正在使用geoLocator软件包,但接收距离有一个问题,当我调用该方法时我得到了null,我知道我必须使用async-wait来等待距离的值,但是我不知道在哪里实施它。
这是我称为获取距离的类:
class Distance {
double distance;
void getDistance(double startLatitude, double startLongitude, double endLatitude,
double endLongitude) async {
try {
distance = await Geolocator().distanceBetween(
startLatitude, startLongitude, endLatitude, endLongitude);
} catch (e) {
print('SE DISPARO EL ERROR DE DISTANCE = $e');
}
}
这是我返回的小部件:
Widget cardList(double userLatitude, double userLongitude) {
double result;
// Method to get the distance
dynamic getDistance(double cardLatitude, double cardLongitude) async {
Distance distancia = Distance();
await distancia.getDistance(
userLatitude, userLongitude, cardLatitude, cardLongitude);
result = distancia.distance;
return result;
}
return StreamBuilder<QuerySnapshot>(
stream: _firestore.collection('salonesInfantiles').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.pink,
),
);
}
final rooms = snapshot.data.documents.reversed;
List<SalonesFeed> listaDeSalones = [];
// List<SalonesFeed> listaDeSalonesDistancia = [];
for (var room in rooms) {
final nombreSalonText = room.data['nombre'];
final salonLatitude = room.data['latitude'];
final salonLongitude = room.data['longitude'];
// This is the method that i dont know how to implement the wait in order to receive the value before the ListView is showed
double distance = getDistance(salonLatitude, salonLongitude);
print('result 2 = $result');
final salonCard = SalonesFeed(
nombreSalon: nombreSalonText,
distanciaSalon: distance,
);
listaDeSalones.add(salonCard);
}
return Expanded(
child: ListView(
children: listaDeSalones,
),
);
},
);
}
我得到了这个结果:
type 'Future<dynamic>' is not a subtype of type 'double'
我也尝试将其设置为Future,但仍然存在null问题
type 'Future<double>' is not a subtype of type 'double'
答案 0 :(得分:0)
getDistance的返回类型应为Future,并且您应等待响应
double distance = await getDistance(salonLatitude, salonLongitude);