一、依赖
dependencies:
# permission 权限处理
permission_handler: ^8.1.0
二、代码
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
class PermissionUtil {
BuildContext _context;
PermissionUtil(this._context);
//在检查之前可以去申请权限
void checkPermission(PermissionStatus status, Permission permission) async {
if (status.isDenied) {
//拒绝了权限
log("拒绝了权限");
showPermissionRequestDialog('您拒绝了申请权限,但是该应用需要该权限,继续吗', permission, false);
} else if (status.isPermanentlyDenied) {
//永久拒绝了权限 提示用户
log("永久拒绝了权限");
showPermissionRequestDialog('您永久拒绝了权限,但是该应用需要该权限,继续吗', permission, true);
} else {
//通过权限申请
log("通过权限申请...");
}
}
void showPermissionRequestDialog(String message, Permission permission, bool gotoAppSettings) {
showDialog(context: _context,
builder: (context) {
return AlertDialog(
title: Text('权限申请'),
content: Container(width: 200, child: Text(message),),
actions: <Widget>[
MaterialButton(onPressed: () {
Navigator.of(context).pop();
}, child: Text('取消')),
MaterialButton(onPressed: () {
Navigator.of(context).pop();
if (gotoAppSettings){
openAppSettings() ;
}else {
requestPermission(context, permission);
}
}, child: Text('确定')),
],
actionsPadding: EdgeInsets.symmetric(horizontal: 8.0),
);
});
}
void requestPermission(BuildContext context, Permission permission) async{
//请求权限
PermissionStatus status = await permission.request();
checkPermission(status, permission);
}
//关闭应用??
void closeApp(){
SystemChannels.platform.invokeMethod("SystemNavigator.pop");
}
}
三、使用
import 'package:flutter/material.dart';
import 'package:flutter_widgets/permission/permission_util.dart';
import 'package:permission_handler/permission_handler.dart';
class PermissionPage extends StatefulWidget {
const PermissionPage({Key? key}) : super(key: key);
@override
_PermissionPageState createState() => _PermissionPageState();
}
class _PermissionPageState extends State<PermissionPage> {
late PermissionUtil _permissionUtil;
@override
void initState() {
super.initState();
_permissionUtil = PermissionUtil(context);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('权限请求'),),
body: Container(
child: Center(
child: Column(
children: [
MaterialButton(
child: Text('申请权限'),
onPressed: () {
_permissionUtil.requestPermission(context, Permission.storage);
}),
Text('请求权限结果:'),
],
)
),
),
);
}
}
四、总结
权限申请基本上是使用第三方插件即可完成,没有什么可以可讲的,但是在使用的时候注意下相关的配置要求。? ? ? ??
|