flutter 动态申请权限

在pubspec.yaml 文件中导入

permission_handler: ^3.2.0
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 _requestPermissions() async {
//  申请权限
  Map 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();
      }
    }
  }

搞定

你可能感兴趣的:(flutter)