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

Flutter中Geolocator.getCurrentPosition方法无返回值问题求助

问题排查及解决步骤

1. 修正代码逻辑错误

现有代码混用await和.then异步写法,且未给getCurrentPosition加await修饰,导致try-catch无法捕获方法抛出的超时异常,异常会直接被异步链路吞掉。请替换为统一的await写法:

Future _getCurrentLocation() async {
  // 先检查定位服务是否开启
  bool isGeolocationAvailable = await Geolocator.isLocationServiceEnabled();
  if (!isGeolocationAvailable) {
    return null;
  }
  // 检查定位权限 缺少这一步是大概率失败原因
  LocationPermission permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied) {
      return null;
    }
  }
  if (permission == LocationPermission.deniedForever) {
    return null;
  }
  try {
    // 模拟器不建议使用LocationAccuracy.best 改成high即可
    Position pos = await Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.high, 
      timeLimit: const Duration(seconds: 10)
    );
    setPosition(pos);
  } catch (error) {
    print(error.toString());
    Position? pos = await Geolocator.getLastKnownPosition();
    if (pos != null) {
      setPosition(pos);
    }
  }
  return null;
}

2. 检查安卓端权限配置

在项目android/app/src/main/AndroidManifest.xml的manifest标签下添加定位权限:

<!-- 精确定位权限 对应LocationAccuracy.high及以上精度 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- 安卓12及以上前台定位权限 如果targetSdkVersion>=31必须添加 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

3. 检查模拟器配置

  • 确认模拟器的定位开关已开启,且给当前应用授予了定位权限
  • 给模拟器手动注入定位坐标:点击模拟器侧边栏的更多按钮(三个点),进入Location面板,搜索任意地址或者手动输入经纬度,点击SET LOCATION保存后再测试,模拟器默认无预置定位坐标会导致定位超时
  • 不要在模拟器上使用LocationAccuracy.best精度,大部分安卓模拟器无法满足该精度的定位要求,会触发超时

4. 辅助验证方案

如果以上步骤操作后仍有问题,可以先用真机运行测试,排除模拟器本身定位模块故障的问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:45:09