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

Flutter中CoreLocation UI无响应错误的解决求助

问题描述

在Flutter中使用默认location包获取当前位置时,遇到CoreLocation错误。设备已开启应用的位置权限,但仅在打开地图时出现该错误,导致函数无法返回当前位置坐标。

完整错误信息

[CoreLocation] This method can cause UI unresponsiveness if invoked on the main thread. Instead, consider waiting for the `-locationManagerDidChangeAuthorization:` callback and checking `authorizationStatus` first.

已尝试操作

  • 执行clean pod install
  • 修改info.plist中的权限设置
  • 查找相关问题,但结果大多涉及Geolocator而非默认location包

相关代码片段

Flutter端获取位置代码

void getCurrentLocation () {
    Location location = Location(); // 执行到此处后不再继续

    location.getLocation().then(
      (location) {
        currentLocation = location;
    });
}

iOS端AppDelegate代码

import UIKit
import Flutter
import GoogleMaps

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GMSServices.provideAPIKey("KEY")
    GeneratedPluginRegistrant.register(with: self)
      
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  
  }

}

解决方案

这个错误的核心是在主线程调用了可能阻塞UI的CoreLocation方法,且未正确等待权限授权回调就直接获取位置。针对默认location包,按以下步骤修复:

  1. 先确认权限状态,再获取位置
    不要初始化Location后直接调用getLocation(),先检查并确认权限已授予,再执行位置获取逻辑。修改Flutter端代码如下:

    void getCurrentLocation() async {
      Location location = Location();
      
      // 检查权限状态
      PermissionStatus permission = await location.hasPermission();
      if (permission == PermissionStatus.denied) {
        permission = await location.requestPermission();
        if (permission != PermissionStatus.granted) {
          // 权限未授予,添加对应处理逻辑
          return;
        }
      }
    
      // 权限确认后获取位置
      try {
        LocationData locData = await location.getLocation();
        currentLocation = locData;
      } catch (e) {
        print("获取位置失败: $e");
      }
    }
    
  2. 监听权限变化回调
    借助location包的权限监听流,确保在权限授予后再触发位置获取,避免主线程阻塞:

    // 监听权限变化
    location.onPermissionChanged.listen((PermissionStatus status) {
      if (status == PermissionStatus.granted) {
        _fetchLocation();
      }
    });
    
    void _fetchLocation() async {
      try {
        LocationData locData = await location.getLocation();
        currentLocation = locData;
      } catch (e) {
        print(e);
      }
    }
    
  3. 完善iOS权限配置
    确保info.plist中已添加对应场景的位置权限描述(按需选择):

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>需要你的位置信息来显示地图</string>
    <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
    <string>需要你的位置信息来提供持续的地图服务</string>
    
  4. 避免UI初始化阶段直接调用
    不要在Widget的initState中立即执行getCurrentLocation(),可以延迟执行或在用户交互(如点击按钮)后触发,降低主线程阻塞概率。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:52:38