我正在尝试使用 firebase 查询来获取附近的位置,并且进展顺利。这是获取附近位置的函数。
Future<List<DocumentSnapshot>> nearbyLocations() async {
CollectionReference collectionRefer =
FirebaseFirestore.instance.collection('locations');
double radius = 10;
String field = 'position';
List<DocumentSnapshot> docList;
GeoFirePoint center = await getCurrentLocation();
// print(center);
Stream<List<DocumentSnapshot>> stream = geo
.collection(collectionRef: collectionRefer)
.within(center: center, radius: radius, field: field, strictMode: true);
stream.listen((List<DocumentSnapshot> documentList) {
if (documentList.length > 0) {
print(documentList[0].data());
docList = documentList;
} else {
return {};
}
});
}
我知道查询将只返回一个数据。所以,我在上面的函数中打印了第一个值。返回 documentList 时会出现问题。
loadData() async {
documentList =
await GeoLocator().nearbyLocations();
}
当我调用上面的函数时,它打印空。但是当我尝试在 nearbyLocations()
中打印时它打印数据。但不是当我调用loadData()
.我将在 ListView 中使用这个返回的数据。
最佳答案
你在混await
,流和then
.这可能太多了,不能同时记住。
首先专注于一种方法。我建议async
/await
因为这是最简单的。
您的 nearLocations 方法不会返回任何内容。您没有定义类型,它也没有返回语句。然而,您似乎希望它返回 Future<>
具有指定类型。
确保提高警告并使用 pedantic包,让您的分析仪在您忘记这些事情时通知您。
当你真正完全声明你的方法时,你的警告应该告诉你你的方法没有返回。
我这里没有编译器或要包含的包,但这似乎是您真正想要的:
Future<List<DocumentSnapshot>> nearbyLocations() async {
final collectionRefer = FirebaseFirestore.instance.collection('locations');
final radius = 10.0;
final field = 'position';
final center = await getCurrentLocation();
final stream = geo
.collection(collectionRef: collectionRefer)
.within(center: center, radius: radius, field: field, strictMode: true);
return stream.first;
}
关于firebase - 一个函数打印该值,但返回时它没有打印在另一个函数上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64568118/