Flutter 使用permission

Flutter 使用permission,第1张

最近Flutter项目中需要使用到高德定位,需要申请定位权限,在这里使用到了permission_handler 。遇到了一些问题记录一下(以定位权限为例)。

获取插件
 在 pubspec.yaml 文件配置
dependencies:
  permission_handler: ^8.2.5
permission_handler | Flutter Package配置权限信息
在Info.plist 文件配置
NSLocationAlwaysAndWhenInUseUsageDescription
	运单打卡需要获取您的位置信息
	NSLocationAlwaysUsageDescription
	运单打卡需要获取您的位置信息
	NSLocationUsageDescription
	运单打卡需要获取您的位置信息
	NSLocationWhenInUseUsageDescription
	运单打卡需要获取您的位置信息

在Podfile文件配置(这一点要注意)
 


post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)

      target.build_configurations.each do |config|
          # You can remove unused permissions here
          # for more infomation: https://github.com/BaseflowIT/flutter-permission-handler/blob/master/permission_handler/ios/Classes/PermissionHandlerEnums.h
          # e.g. when you don't need camera permission, just add 'PERMISSION_CAMERA=0'
          config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
            '$(inherited)',

            ## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
            'PERMISSION_LOCATION=1',

          ]

        end
  end
end

调用申请权限
 


  /// 动态申请定位权限
  void requestPermission() async {
    // 申请权限
    bool hasLocationPermission = await requestLocationPermission();
    if (hasLocationPermission) {
      // 权限申请通过
    } else {

    }
  }


  /// 申请定位权限
  /// 授予定位权限返回true, 否则返回false
  Future requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

4. 成功调起申请权限

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/990343.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存