权限处理
2023-09-04 本文已影响0人
Crassus
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
class PermissionHelper {
static VoidCallback defaultCall = () {};
///检查权限
static void check(List<Permission> permissionList,
{String? errMsg,
VoidCallback? onSuccess,
VoidCallback? onFailed,
VoidCallback? onOpenSetting}) async {
bool flag = true;
for (var value in permissionList) {
var status = await value.status;
if (!status.isGranted) {
flag = false;
break;
}
}
if (!flag) {
PermissionStatus permissionStatus =
await requestPermission(permissionList);
if (permissionStatus.isGranted) {
onSuccess != null ? onSuccess() : defaultCall();
} else if (permissionStatus.isDenied) {
onFailed != null ? onFailed() : defaultCall();
} else if (permissionStatus.isPermanentlyDenied) {
onOpenSetting != null ? onOpenSetting() : defaultCall();
} else if (permissionStatus.isRestricted) {
//IOS单独处理
onOpenSetting != null ? onOpenSetting() : defaultCall();
} else if (permissionStatus.isLimited) {
//IOS单独处理
onOpenSetting != null ? onOpenSetting() : defaultCall();
}
}else{
onSuccess != null ? onSuccess() : defaultCall();
}
}
//申请权限
static Future<PermissionStatus> requestPermission(
List<Permission> permissionList) async {
Map<Permission, PermissionStatus> statuses = await permissionList.request();
PermissionStatus currentPermissionStatus = PermissionStatus.granted;
statuses.forEach((key, value) {
if (!value.isGranted) {
currentPermissionStatus = value;
return;
}
});
return currentPermissionStatus;
}
static checkPermission(List<Permission> requests,
Function(bool)? successCallback, BuildContext context) {
PermissionHelper.check(
requests,
onSuccess: () {
// 权限已授予,执行成功逻辑
successCallback?.call(true);
},
onFailed: () {
requestAgainAlert(context, callback: () async {
// 权限未授予,执行失败逻辑
PermissionStatus status = await requestPermission(requests);
successCallback?.call(status.isGranted);
});
},
onOpenSetting: () {
requestAgainAlert(context, callback: () {
// 权限未授予,执行失败逻辑
openAppSettings();
});
},
);
}
static requestAgainAlert(BuildContext context, {Function()? callback}) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('权限未授予'),
content: const Text('您需要授予"定位权限"才能继续使用该功能。'),
actions: [
TextButton(
onPressed: () {
callback?.call();
Navigator.of(context).pop();
},
child: const Text('确定'),
),
],
);
},
);
}
}
使用
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
requestLocationPermission();
}
Future<void> requestLocationPermission() async {
await Future.delayed(Duration.zero); // 延迟到下一帧
final requests = [Permission.locationWhenInUse];
// ignore: use_build_context_synchronously
PermissionHelper.checkPermission(requests, successCallback, context);
}
// 处理权限申请结果业务
successCallback(bool success) async {
if (success == false) {
print("error $success");
requestLocationPermission();
return;
}