Flutter Geolocator包无法获取当前位置问题求助
解决Geolocator getCurrentPosition无返回结果问题
我在学习Flutter,跟着londonappbrewery的Flutter课程重构Clima项目时遇到问题:安装了geolocator ^9.0.2包,调用getCurrentPosition方法后没有任何结果。当前使用Flutter 3.10.6,在物理设备测试,已手动授予权限,AndroidManifest.xml也添加了相关权限,但问题依旧。
相关代码
void getLocation() async { LocationPermission permission = await Geolocator.requestPermission(); print(permission); Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low); print(position); }
AndroidManifest.xml添加的权限
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
排查与解决方法
完善权限校验逻辑
仅申请权限不判断最终状态,可能导致权限未真正授权就执行位置获取。需先检查权限状态,确认允许后再继续执行。补充必要权限
Android 10及以上版本,获取位置还需前台位置权限,在AndroidManifest.xml中添加:<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />即使设置了
LocationAccuracy.low,部分设备仍需要该权限配合才能正常获取位置。检查位置服务状态
物理设备若关闭了位置服务,即便有权限也无法获取位置。代码中需添加服务状态检查,未开启时引导用户打开设置。捕获异步异常
原代码未处理异常,无法定位具体错误(如权限被拒、服务超时等),需添加try-catch捕获异常信息。
修改后的完整代码
void getLocation() async { try { // 先检查已有权限状态 LocationPermission permission = await Geolocator.checkPermission(); if (permission == LocationPermission.denied) { permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied) { print("位置权限被拒绝"); return; } } // 检查设备位置服务是否开启 bool isLocationEnabled = await Geolocator.isLocationServiceEnabled(); if (!isLocationEnabled) { print("设备位置服务未开启"); // 引导用户打开位置设置 await Geolocator.openLocationSettings(); return; } // 获取位置 Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low); print(position); } catch (e) { print("获取位置失败: $e"); } }
内容的提问来源于stack exchange,提问作者Xinying Zhou
相关产品推荐
相关产品推荐

