Flutter:未处理的异常:用户拒绝访问设备位置的权限

问题描述 投票:0回答:6

我正在尝试在 flutter 中获取用户当前位置,但它显示地图,但没有指向我当前的位置。我已在 AndriodManifest 文件中添加了所有必需的权限。

这里是快照

这是日志

I/Google Maps Android API(24140): Google Play services package version: 201817022
E/GoogleMapController(24140): Cannot enable MyLocation layer as location permissions are not granted
D/HostConnection(24140): HostConnection::get() New Host Connection established 0xefab0ec0, tid 25110
E/flutter (24140): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: User denied permissions to access the device's location.
E/flutter (24140): #0      MethodChannelGeolocator._handlePlatformException
package:geolocator_platform_interface/…/implementations/method_channel_geolocator.dart:242
E/flutter (24140): #1      MethodChannelGeolocator.getCurrentPosition
package:geolocator_platform_interface/…/implementations/method_channel_geolocator.dart:124
E/flutter (24140): <asynchronous suspension>
E/flutter (24140): #2      _locationState.locatepostion
package:map_app/abc.dart:26
E/flutter (24140): <asynchronous suspension>
W/System  (24140): A resource failed to call release.

代码

  Completer<GoogleMapController> _controllerGoogleMap=Completer();
  late GoogleMapController newGoogleMapController;
  double mapbottompadding=0;

  GlobalKey<ScaffoldState> scaffoldkey=new GlobalKey<ScaffoldState>();
  late Position currentpositon;
  var geolocator=Geolocator();

  void locatepostion() async{
    Position position=await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    currentpositon=position;  // this is line 26, it is point before await

    LatLng latLngPosition=LatLng(position.latitude,position.longitude);

    CameraPosition cameraPosition=new CameraPosition(target: latLngPosition,zoom: 14);
    newGoogleMapController.animateCamera(CameraUpdate.newCameraPosition(cameraPosition));
  }

  static final CameraPosition googlepostion=CameraPosition(target: LatLng(37.4249,-122.0657));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(children: [
        GoogleMap(
          padding: EdgeInsets.only(bottom: mapbottompadding),
          mapType: MapType.normal,
          myLocationButtonEnabled: true,
          myLocationEnabled: true,
          zoomControlsEnabled: true,
          zoomGesturesEnabled: true,
           initialCameraPosition: googlepostion,
          onMapCreated: (GoogleMapController controller){
              _controllerGoogleMap.complete(controller);
              newGoogleMapController=controller;
              setState(() {
                mapbottompadding=300.0;
              });         
              locatepostion();
         

这是我的输出

--------更新

它在andriod手机上完美运行,但在模拟器上无法运行。

flutter geolocation google-maps-android-api-2
6个回答
34
投票
 LocationPermission permission;
   permission = await Geolocator.requestPermission();

首先使用此请求许可。


16
投票
class GeolocatorService {
  Future<Position?> determinePosition() async {
    LocationPermission permission;
    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.deniedForever) {
        return Future.error('Location Not Available');
      }
    } else {
      throw Exception('Error');
    }
    return await Geolocator.getCurrentPosition();
  }
}

8
投票

这是地理定位器中出现的常见问题,尤其是。当您未授予设备权限时。默认情况下它是禁用的,因此您必须在调用

locatePosition()
时请求它。请记住,地理定位器包包装在 google_maps_flutter 下。 因此,要解决位置问题,请确保执行以下操作

class _MapScreenState extends State<MapScreen> {
void locatePosition() async {
    bool isLocationServiceEnabled = await Geolocator.isLocationServiceEnabled();
    
    await Geolocator.checkPermission();
    await Geolocator.requestPermission();
    
    Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    
    currentPosition = position;
    LatLng latLngPosition = LatLng(position.latitude, position.longitude);
        
    // Ask permission from device
    Future<void> requestPermission() async {
    await Permission.location.request();
    }
}

1
投票

要解决此问题,请按照以下步骤操作:

  1. 为各个平台添加权限。
  • Android:项目->android->src->main->AndroidManifest.xml 在标签内添加权限

  • 单击按钮即可调用方法

    void getLocation() 异步{
    LocationPermission权限;
    权限 = 等待 Geolocator.requestPermission();
    位置position =等待Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    打印(位置); //在这里你会得到你的纬度和经度
    }

  • 这个解决方案对我有用,希望对您也有帮助。

    另请检查您的许可请求。 例如:您的权限状态在此按钮下; “找到我的位置”

    ElevatedButton(onPressed: () async {
              PermissionStatus location = await Permission.location.request();
              locationInfo();
            }, child: const Text("Find my location")),
    

    在处理 udemy 项目时遇到这个问题clima_flutter

    启动应用程序时出现以下错误

    Flutter: Unhandled Exception: User denied permissions to access the device's location
    

    我的flutter版本是3.16.9

    flutter --version
    Flutter 3.16.9 • channel stable • https://github.com/flutter/flutter.git
    

    我的dart版本是3.2.6

      dart --version
    Dart SDK version: 3.2.6 (stable) (Wed Jan 24 13:41:58 2024 +0000) on "macos_x64"
    

    我使用的gradle包装器版本是7.5

    distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-all.zip
    

    使用以下地理定位器依赖项

    geolocator: ^11.0.0
    

    尝试在应用程序启动时加载当前位置。

    class _LoadingScreenState extends State<LoadingScreen> {
      @override
      void initState() {
        super.initState();
        getLocation();
      }
    

    其中 getLocation 调用 getCurrentLocation() 方法

    Future<void> getLocation() async {
        await Location().getCurrentLocation();
     }
    

    先决条件:

    对于 android,应在 AndroidManifest.xml 中添加以下权限请求

     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
            <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    

    对于 ios,在 ios/Runner/info.plist

    <key>NSLocationWhenInUseUsageDescription</key>
        <string>This app needs access to location when open.</string>
    

    我的代码仍然失败。下面的实现是一个修复。我们首先检查权限是否可用,如果没有,我们会提前请求。

    Future<void> getCurrentLocation() async {
        try {
          LocationPermission permission = await Geolocator.checkPermission();
          if (permission == LocationPermission.denied) {
            print("No permission, requesting one");
            permission = await Geolocator.requestPermission();
            if (permission == LocationPermission.deniedForever) {
              return Future.error('Location Not Available');
            }
          } 
            print("Found permission to get location");
            Position position = await Geolocator.getCurrentPosition(
                desiredAccuracy: LocationAccuracy.low);
            latitude = position.latitude;
            longitude = position.longitude;
          
        } catch (e) {
          print(e);
        }
      }
    

    通过此实现,模拟器上会提示请求对话框以提供位置权限。


0
投票

另请检查您的许可请求。 例如:您的权限状态在此按钮下; “找到我的位置”

ElevatedButton(onPressed: () async {
          PermissionStatus location = await Permission.location.request();
          locationInfo();
        }, child: const Text("Find my location")),

0
投票

在处理 udemy 项目时遇到这个问题clima_flutter

启动应用程序时出现以下错误

Flutter: Unhandled Exception: User denied permissions to access the device's location

我的flutter版本是3.16.9

flutter --version
Flutter 3.16.9 • channel stable • https://github.com/flutter/flutter.git

我的dart版本是3.2.6

  dart --version
Dart SDK version: 3.2.6 (stable) (Wed Jan 24 13:41:58 2024 +0000) on "macos_x64"

我使用的gradle包装器版本是7.5

distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-all.zip

使用以下地理定位器依赖项

geolocator: ^11.0.0

尝试在应用程序启动时加载当前位置。

class _LoadingScreenState extends State<LoadingScreen> {
  @override
  void initState() {
    super.initState();
    getLocation();
  }

其中 getLocation 调用 getCurrentLocation() 方法

Future<void> getLocation() async {
    await Location().getCurrentLocation();
 }

先决条件:

对于 android,应在 AndroidManifest.xml 中添加以下权限请求

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

对于 ios,在 ios/Runner/info.plist

<key>NSLocationWhenInUseUsageDescription</key>
    <string>This app needs access to location when open.</string>

我的代码仍然失败。下面的实现是一个修复。我们首先检查权限是否可用,如果没有,我们会提前请求。

Future<void> getCurrentLocation() async {
    try {
      LocationPermission permission = await Geolocator.checkPermission();
      if (permission == LocationPermission.denied) {
        print("No permission, requesting one");
        permission = await Geolocator.requestPermission();
        if (permission == LocationPermission.deniedForever) {
          return Future.error('Location Not Available');
        }
      } 
        print("Found permission to get location");
        Position position = await Geolocator.getCurrentPosition(
            desiredAccuracy: LocationAccuracy.low);
        latitude = position.latitude;
        longitude = position.longitude;
      
    } catch (e) {
      print(e);
    }
  }

通过此实现,模拟器上会提示请求对话框以提供位置权限。

© www.soinside.com 2019 - 2024. All rights reserved.