在pubspec.yaml 文件中导入
permission_handler: ^3.2.0
Android 在mainfest里添加对应权限
<uses-permission android:name="android.permission.CAMERA"/>
Ios 在info.plist添加对应的权限
<key>NSCameraUsageDescription</key>
<string>翻呀需要您的同意才能使用相机</string>
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: Scaffold(
body: Center(
child: RaisedButton(
onPressed: _requestPermissions,
child: Text('点击申请权限'),
),
),
),
);
}
}
Future<bool> _requestPermissions() async {
// 申请权限
Map<PermissionGroup, PermissionStatus> permissions =
await PermissionHandler().requestPermissions([
PermissionGroup.storage,
PermissionGroup.camera,
]);
// 申请结果
PermissionStatus permissionStatus =
await PermissionHandler().checkPermissionStatus(PermissionGroup.camera);
if (permissionStatus == PermissionStatus.granted) {
print('申请成功');
} else {
print('申请被拒绝');
bool isShow = await PermissionHandler()
.shouldShowRequestPermissionRationale(PermissionGroup.camera);
if (!isShow) {
print('当前权限已被禁用申请,请在设置中手动开启后退出重新进入程序');
await PermissionHandler().openAppSettings();
} else {
PermissionStatus ps = await PermissionHandler()
.checkPermissionStatus(PermissionGroup.camera);
if (ps == PermissionStatus.granted) {
print('登录成功!');
} else {
_requestPermissions();
}
}
}
搞定