flutter - 颤振——带有地理编码器包
问题描述
我需要从经度和纬度中获取城市名称。我没有找到一个包来做到这一点,所以我使用 location 包来获取 Long 和 Lat 并使用地理编码器来获取城市名称。
但我一直有这个错误并且没有结果:
[错误:flutter/lib/ui/ui_dart_state.cc(177)] 未处理的异常:PlatformException(失败,失败,空,空)
而这之后在控制台上:<异步挂起>
这是我的代码:
class _ProfileScreenState extends State<ExploreScreen> {
dynamic currentLocation;
double userLongitude;
double userLatitude;
Coordinates coordinates;
var addresses;
var first;
@override
initState() {
super.initState();
_getCurrentLongAndLat();
_getCurrentPosition(userLatitude, userLatitude);
}
Future _getCurrentLongAndLat() async {
currentLocation = LocationData;
var error;
var location = new Location();
try {
currentLocation = await location.getLocation();
userLatitude = currentLocation.latitude;
userLongitude = currentLocation.longitude;
print('$userLatitude $userLatitude');
} on PlatformException catch (e) {
if (e.code == 'PERMISSION_DENIED') {
error = 'Permission denied';
}
currentLocation = null;
}
}
Future _getCurrentPosition(double long, double lat) async {
coordinates = new Coordinates(userLatitude, userLongitude);
addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
print(addresses.first);
}
}
解决方案
我意识到颤振包地理定位器和位置有时会相互冲突。
尝试使用地理定位器获取您当前的位置:
Future _getCurrentPosition() async {
Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high).then((Position position) {
setState(() {
_currentPosition = position;
userLongitude = position.longitude;
userLatitude = position.latitude;
});
});
}
它是一个 Future,因此您可以使用 await 来真正等待结果,然后使用 userLat 和 userLng 调用 getAddress 函数。
推荐阅读
- python - 如果在 pytest 上启用 -W 错误,则向 stderr 打印警告
- sql - 一个表可以拥有的最大有用索引数?
- android - 将 Gradle 更新到 3.1.1 版后,Android 库无法正常工作
- php - 通过 PHP删除标签并保留标签内容?
- linux - 在循环中使用带有 sql 输出的 for
- arrays - [number, number] 是元组类型吗?
- php - Laravel 全名检查它是否真的完整
- plsql - “ORA-24344:编译成功”错误是什么意思?
- c# - NoesisGUI - 在 Noesis.Image 元素中加载 PNG
- hibernate - 在 HQL 中减去日期