flutter-使用permission_handler进行系统权限的申请和操作
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: PermissionPage(),
);
}
}
class PermissionPage extends StatefulWidget {
@override
_PermissionPageState createState() => _PermissionPageState();
}
class _PermissionPageState extends State<PermissionPage> {
PermissionStatus _permissionStatus = PermissionStatus.denied;
Future<void> checkPermission() async {
final PermissionStatus permissionStatus = await Permission.camera.status;
setState(() {
_permissionStatus = permissionStatus;
});
}
Future<void> requestPermission() async {
final PermissionStatus permissionStatus = await Permission.camera.request();
setState(() {
_permissionStatus = permissionStatus;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Permission Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Camera permission status: $_permissionStatus\n'),
RaisedButton(
child: Text('Check permission status'),
onPressed: checkPermission,
),
RaisedButton(
child: Text('Request permission'),
onPressed: requestPermission,
),
],
),
),
);
}
}
这段代码演示了如何在Flutter应用中使用permission_handler
插件来检查和请求相机权限。代码首先定义了一个_PermissionPageState
状态类,其中包含了检查和请求权限的异步函数。在build
方法中,它创建了两个按钮,分别用于触发这些函数。这个例子简单明了,对开发者有很好的指导作用。
评论已关闭