You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Geolocator 7.7.0 iOS运行正常 Android端无报错无法获取定位

问题根因

  • 你使用的Geolocator 7.7.0版本未完成Android 12的全量适配,其中getCurrentPosition方法在Android 12设备上未设置超时时会出现无限挂起的已知bug,无返回也不抛异常。
  • 你开启了forceAndroidLocationManager: true参数,强制调用Android原生LocationManager实现定位,Android 12对原生定位模块的调用逻辑做了破坏性变更,7.x版本的Geolocator未适配该逻辑。
  • AndroidManifest.xml缺少Android 12专属的定位相关配置,同时部分Android 12设备/模拟器默认仅授予应用模糊定位权限,你设置的LocationAccuracy.best要求精确定位权限,权限不匹配会导致定位请求卡住。

解决方案

方案一(优先推荐):升级Geolocator版本

直接升级到geolocator: ^8.2.0及以上版本,该版本已完整适配Android 12定位规则,修复了无响应bug,同时默认使用兼容性更好的Google Play融合定位服务,无需额外修改核心逻辑,仅需注意参数调整:

  • forceAndroidLocationManager参数已废弃,替换为androidSettings配置:
return await Geolocator.getCurrentPosition(
  desiredAccuracy: LocationAccuracy.best,
  // 替换为以下配置,不需要强制原生定位的话可以删掉forceLocationManager配置
  androidSettings: const AndroidSettings(
    forceLocationManager: true,
    timeLimit: Duration(seconds: 10),
  ),
  // iOS配置可选
  iosSettings: const IOSSettings(
    accuracy: LocationAccuracy.best,
  ),
).then((Position position) {
  setState(() {
    gcStartingLatitudeGEODEG.text = position.latitude.toStringAsFixed(6);
    gcStartingLongitudeGEODEG.text = position.longitude.toStringAsFixed(6);
  });
}).catchError((e) {
  print(e);
});

方案二(不升级版本的临时修复)

如果需要保留7.7.0版本,按以下步骤修改:

  1. 给getCurrentPosition增加超时配置,避免无限挂起
return await Geolocator.getCurrentPosition(
  desiredAccuracy: LocationAccuracy.best,
  forceAndroidLocationManager: true,
  timeLimit: const Duration(seconds: 10), // 新增超时配置,超时时会自动抛错进入catchError
).then(...).catchError(...);
  1. 关闭forceAndroidLocationManager参数(设为false),优先使用融合定位,兼容性更好。
  2. 补充AndroidManifest.xml配置,新增Android 12专属权限:
<!-- 原有定位权限保留 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<!-- 新增Android 12前台定位服务配置 -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<service
    android:name="com.baseflow.geolocator.location.ForegroundLocationService"
    android:foregroundServiceType="location" />
  1. 调整权限校验逻辑,增加模糊定位适配:权限通过后判断如果仅获得模糊定位权限,自动降低定位精度到LocationAccuracy.high或LocationAccuracy.balanced。
  2. 补充异步调用的await关键字,避免异常无法捕获:
onPressed: () async {
  await _determineCurrentPositionStarting(); // 新增await
},

额外校验项

  • 检查Android 12设备/模拟器的应用权限设置,确认已经授予精确定位权限,而非仅模糊定位。
  • 开启设备的Wi-Fi/蓝牙扫描开关,可大幅提升原生定位的获取速度,避免超时。

内容的提问来源于stack exchange,提问作者James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 03:54:01