firebase - 一个函数打印该值,但返回时它没有打印在另一个函数上
问题描述
我正在尝试使用 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()
。我将在列表视图中使用这个返回的数据。
解决方案
你正在混合await
,流和then
。这可能太多了,不能同时记住。
首先专注于一种方法。我建议async
/await
因为这是最简单的。
您的 nearLocations 方法不会返回任何内容。您没有定义类型,它也没有返回语句。但是,您似乎希望它返回Future<>
具有指定类型的 a。
确保您提高警告并使用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;
}
推荐阅读
- php - jQuery 选择器在 php if 语句中捕获类
- wordpress - 在 Wordpress 中为单个帖子上传多个图像
- c# - 如果有的话,我可以改用将所有内容都设为 readkey 吗?我只需要在输入“q”时退出;
- reactjs - 无法为 github.io 投资组合页面选择 src
- mongodb - 如何使用复杂函数对 mongo 进行投影和排序
- javascript - 如何使用react js在另一个页面显示html表单提交的信息?
- sql - ORDER BY 项目必须出现在选择列表中
- java - Liquibase 根据表名前缀在 db 上生成更改日志
- amazon-web-services - 带有日志的 cloudwatch 指标过滤器警报
- python - 如何在 Python 的 discord.Colour 中使用 RGB 代码?