未处理的异常:PlatformException(PERMISSION_DENIED,拒绝访问位置数据,为null)

时间:2020-07-14 06:35:58

标签: flutter

   it give the exception when i get the current  location of the user . my flutter version :-  
    v1.17.4, and  my info.plist code is given below. geolocator: ^5.3.2+2


Future<Position> locateUser() async {
  return  await Geolocator()
      .getCurrentPosition(desiredAccuracy: LocationAccuracy.low,locationPermissionLevel: 
         GeolocationPermission.location);
              }
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access to location when in the background.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app needs access to location when open and in the background.</string>


 

1 个答案:

答案 0 :(得分:1)

回复可能晚了,但我也遇到了同样的问题,即该应用在 iOS 中没有请求许可,而在 android 中运行良好。

因为没有请求许可,这就是许可代码不适用于 iOS 的原因。我找到了一个名为“location_permissions”的包,可以用来手动请求权限。

步骤如下

  1. 在“pubspec.yaml”中添加“location_permissions: 3.0.0+1”这个依赖项。请注意,我是为 flutter 1.22.0 做的,所以对于 flutter 2.0,这可能是一个问题。

  2. 导入文件中的包

    import 'package:location_permissions/location_permissions.dart';
    
  3. 在您要请求许可的页面上添加以下代码。 (最好在应用的第一页添加。)

      @override
       void initState() {
        ....
       if (Platform.isIOS) {
         location_permission();
       }
       ....
    }
    
  4. 在同一个文件中添加以下两个方法

    void location_permission() async {
     final PermissionStatus permission = await _getLocationPermission();
     if (permission == PermissionStatus.granted) {
       final position = await geolocator.getCurrentPosition(
           desiredAccuracy: LocationAccuracy.best);
    
       // Use the position to do whatever...
     }
    }
    
    Future<PermissionStatus> _getLocationPermission() async {
     final PermissionStatus permission = await LocationPermissions()
         .checkPermissionStatus(level: LocationPermissionLevel.location);
    
     if (permission != PermissionStatus.granted) {
       final PermissionStatus permissionStatus = await LocationPermissions()
           .requestPermissions(
               permissionLevel: LocationPermissionLevel.location);
    
       return permissionStatus;
     } else {
       return permission;
     }
    }
    

就是这样,您现在应该在 iOS 应用程序中看到一个弹出窗口,要求您获得位置许可。