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

Flutter中申请位置权限后始终返回Denied问题排查

问题排查与修复方案

核心问题
你的代码存在两个逻辑错误导致权限判断失效:

  • 同时混用了await和then,打乱了异步操作的执行顺序
  • 在then回调中判断的是初始化状态的locationPermissionStatus变量,而非权限请求返回的最新结果

当你选择「While Using the App」后,then回调触发时,全局的locationPermissionStatus还没被更新为新的权限状态(依然是初始的denied),所以判断条件永远不成立,才会一直弹出“not granted”提示。

修复后的代码
改用纯await方式处理异步请求,直接基于返回的最新状态做判断:

Future<void> checkLocationPermission(
  BuildContext context, UserCredential userCredential) async {
  // 获取权限请求的最新状态
  final status = await permission_status.Permission.location.request();
  
  if (status.isGranted) {
    displayToast("granted");
    await getCurrentLocation(context, userCredential);
    // 若需要更新全局变量,在这里赋值
    locationPermissionStatus = status;
  } else {
    displayToast("not granted");
    locationPermissionStatus = status;
  }
}

额外注意事项

  • 你的Android Manifest配置已经包含了前台位置权限(ACCESS_FINE_LOCATION、ACCESS_COARSE_LOCATION),对应「While Using the App」选项,这部分配置是正确的。
  • 如果后续需要申请后台位置权限,需要单独调用permission_status.Permission.locationAlways.request(),并确保Manifest中ACCESS_BACKGROUND_LOCATION权限已配置。
  • 日常开发中尽量避免await和then混合使用,异步逻辑会更清晰易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 20:20:26