Flutter 地理定位器权限

Kos*_*osh 3 geolocation flutter

我的代码是:

class _LoadingScreenState extends State<LoadingScreen> {
  void getLocation() async {
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.low);
    print(position);
  }
Run Code Online (Sandbox Code Playgroud)

我在 Android 清单中添加了以下内容:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Run Code Online (Sandbox Code Playgroud)

Android 模拟器,GPS 已打开。

尝试访问地理位置后,我收到错误:

E/flutter ( 5034): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: User denied permissions to access the device's location.
E/flutter ( 5034): #0      MethodChannelGeolocator.getCurrentPosition (package:geolocator_platform_interface/src/implementations/method_channel_geolocator.dart:127:7)
E/flutter ( 5034): <asynchronous suspension>
E/flutter ( 5034): #1      _LoadingScreenState.getLocation (package:clima/screens/loading_screen.dart:11:25)
E/flutter ( 5034): <asynchronous suspension>
Run Code Online (Sandbox Code Playgroud)

Settings - Security & location - Privacy - Location - App level permissions我的应用程序中,权限已关闭。

打开后我收到一个请求:

在此输入图像描述

为什么会发生这种情况?

这里https://pub.dev/packages/geolocator指出

当您尝试通过 getCurrentPosition 或 getPositionStream 方法获取位置时,地理定位器将自动尝试请求权限。不过,我们确实提供了允许您手动处理请求权限的方法。

权限不是应该根据权限请求中的选择来设置吗?

我在 iOS 上遇到了几乎相同的问题:在“设置”-“隐私”-“位置服务”中,我的应用程序权限设置为“使用时”。尝试访问地理位置后,我收到对话框窗口,但出现错误:

[VERBOSE-2:ui_dart_state.cc(209)] 未处理的异常:用户拒绝访问设备位置的权限。#0 MethodChannelGeolocator.getCurrentPosition (包:geolocator_platform_interface/src/implementations/method_channel_geolocator.dart:127:7) #1 _LoadingScreenState.getLocation (包:clima/screens/loading_screen.dart:11:25)

但为什么?

Meh*_*idi 12

我迟到了,但它对其他开发人员可能有用。

bool serviceEnabled;
LocationPermission permission;

// Test if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();


permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied) {
        Get.snackbar('', 'Location Permission Denied');
        // Permissions are denied, next time you could try
        // requesting permissions again (this is also where
        // Android's shouldShowRequestPermissionRationale
        // returned true. According to Android guidelines
        // your App should show an explanatory UI now.
        return Future.error('Location permissions are denied');
      }
    }

if (permission == LocationPermission.deniedForever) {
 // Permissions are denied forever, handle appropriately.
 return Future.error(
     'Location permissions are permanently denied, we cannot request permissions.');
}
return Geolocator.getCurrentPosition(
    desiredAccuracy: LocationAccuracy.high);
Run Code Online (Sandbox Code Playgroud)

只需去掉isServiceEnabled勾选即可,当您请求权限时,它会自动要求用户启用设备定位服务。