【问题标题】:Flutter - Re ask location permission after deniedFlutter - 拒绝后重新询问位置权限
【发布时间】:2020-01-14 00:05:24
【问题描述】:

我目前正在使用位置包来检索用户的当前位置。如果用户拒绝此请求,我希望稍后在需要他们的位置时能够在应用中重新请求这些权限。

initPlatformState() async {
    await _locationService.changeSettings(
        accuracy: LocationAccuracy.HIGH, interval: 1000);


  LocationData location;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      bool serviceStatus = await _locationService.serviceEnabled();
      print("Service status: $serviceStatus");
      if (serviceStatus) {
        _permission = await _locationService.requestPermission();
        print("Permission: $_permission");

        if (_permission) {
          location = await _locationService.getLocation();
        }
      } else {
        bool serviceStatusResult = await _locationService.requestService();
        print("Service status activated after request: $serviceStatusResult");
        if (serviceStatusResult) {
          initPlatformState();
        }
      }
    } on PlatformException catch (e) {
      print(e);
      if (e.code == 'PERMISSION_DENIED') {
        error = e.message;
        print(error);
      } else if (e.code == 'SERVICE_STATUS_ERROR') {
        error = e.message;
        print(error);
      }
      location = null;
    }

    setState(() {
      _currentLocation = location;
    });
  }

上面的代码是在应用程序的初始化状态下运行的,并且总是在第一次运行应用程序时执行。

第一次运行时,当权限屏幕出现时,如果您授予权限,一切都会按预期工作,并根据需要检索位置。如果您拒绝该权限,则权限为“假”,正如预期的那样。但是,如果您重新打开应用程序,它只会检索 "Service Status: True" 并卡在行上

_permission = await _locationService.requestPermission();

并且永远不会再进步。我期待在执行上述代码时,“请分享您的位置”屏幕会重新出现,但似乎因为用户在首次启动时拒绝了它,它不会重新出现。因此,在更改此设置之前无法使用该应用程序。

有没有办法让这条消息重新出现?还是我必须引导用户打开设置并启用位置权限?

【问题讨论】:

    标签: flutter permissions geolocation location


    【解决方案1】:

    您可以在 initState 中将 initPlatformState() 包装在 setState 中

          @override
    void initState() { 
      super.initState();
      setState(() {
         initPlatformState()
      });
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 2021-10-31
      • 1970-01-01
      • 1970-01-01
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多