Flutter权限管理插件flutter_easy_permission的使用

发布于 1周前 作者 yuanlaile 来自 Flutter

Flutter权限管理插件flutter_easy_permission的使用

简介

flutter_easy_permission 是一个用于 Flutter 的权限管理插件。它是一个对 easypermissions 库的封装,支持 Android 和 iOS 平台。

  • 平台支持
    • ✅ Android
    • ✅ iOS

使用方法

配置权限

Android

在项目的根目录下打开 android/app/src/main/AndroidManifest.xml 文件,并配置你需要的权限:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="xyz.bczl.flutter.easy_permission_example">
    <!-- 配置权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.CAMERA"/>
    <application
        android:label="flutter_easy_permission_example"
        android:icon="@mipmap/ic_launcher">
        <!-- 其他配置 -->
    </application>
</manifest>

详细说明请参见 官方文档

iOS

在项目的根目录下打开 ios/Runner/Info.plist 文件,并配置你需要的权限:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <!-- 配置权限 -->
    <key>NSCameraUsageDescription</key>
    <string>解释为什么需要该权限</string>
    <!-- 其他配置 -->
</dict>
</plist>

注意替换 <string> 标签的内容,以向用户解释为什么需要该权限。

详细说明请参见 官方文档

ios/Podfile 文件中添加所需的权限库:

target 'Runner' do
  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
  # 添加你需要的权限库
  pod 'EasyPermissionX/Camera'
end

你可以集成以下库:

pod 'EasyPermissionX/Camera'
pod 'EasyPermissionX/Photo'
pod 'EasyPermissionX/Contact'
pod 'EasyPermissionX/Location'
pod 'EasyPermissionX/Reminder'
pod 'EasyPermissionX/Calendar'
pod 'EasyPermissionX/Microphone'
pod 'EasyPermissionX/Health'
pod 'EasyPermissionX/Net'
pod 'EasyPermissionX/Tracking'
pod 'EasyPermissionX/Media'
pod 'EasyPermissionX/Notification'
pod 'EasyPermissionX/Bluetooth'

配置完成后,在项目的 ios 目录下运行以下命令:

pod install

检查权限

const permissions = [Permissions.CAMERA];
const permissionGroup = [PermissionGroup.Camera];

bool ret = await FlutterEasyPermission.has(perms: permissions, permsGroup: permissionGroup);

请求权限

FlutterEasyPermission.request(
    perms: permissions, 
    permsGroup: permissionGroup, 
    rationale: "测试需要这些权限"
);

处理回调

void initState() {
  super.initState();
  _easyPermission = FlutterEasyPermission()
    ..addPermissionCallback(
      onGranted: (requestCode, perms, perm) {
        debugPrint("Android 获得授权:$perms");
        debugPrint("iOS 获得授权:$perm");
      },
      onDenied: (requestCode, perms, perm, isPermanent) {
        if (isPermanent) {
          FlutterEasyPermission.showAppSettingsDialog(title: "Camera");
        } else {
          debugPrint("Android 授权失败:$perms");
          debugPrint("iOS 授权失败:$perm");
        }
      },
      onSettingsReturned: () {
        FlutterEasyPermission.has(perms: permissions, permsGroup: []).then(
          (value) => value
            ? debugPrint("已获得授权:$permissions")
            : debugPrint("未获得授权:$permissions")
        );
      }
    );
}

void dispose() {
  _easyPermission.dispose();
  super.dispose();
}

isPermanent 返回 true 时,表示系统不会在请求权限时弹出授权对话框,因此你可能需要自己弹出一个对话框提示用户,如果必须使用此功能,可以引导用户去系统设置页面重新开启权限。

在 Android 上,你可能还需要实现 onSettingsReturned 回调函数来更好地处理权限交互。它是 showAppSettingsDialog 被调用后的回调。

示例

以下是一个完整的示例代码:

import 'package:flutter/material.dart';
import 'package:flutter_easy_permission/easy_permissions.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  static const permissions = [Permissions.CAMERA];
  static const permissionGroup = [PermissionGroup.Camera];
  late FlutterEasyPermission _easyPermission;

  @override
  void initState() {
    super.initState();
    _easyPermission = FlutterEasyPermission()
      ..addPermissionCallback(
        onGranted: (requestCode, perms, perm) {
          debugPrint("android获得授权:$perms");
          debugPrint("iOS获得授权:$perm");
        },
        onDenied: (requestCode, perms, perm, isPermanent) {
          if (isPermanent) {
            FlutterEasyPermission.showAppSettingsDialog(title: "Camera");
          } else {
            debugPrint("android授权失败:$perms");
            debugPrint("iOS授权失败:$perm");
          }
        },
        onSettingsReturned: () {
          FlutterEasyPermission.has(perms: permissions, permsGroup: []).then(
            (value) => value
              ? debugPrint("已获得授权:$permissions")
              : debugPrint("未获得授权:$permissions")
          );
        }
      );
  }

  @override
  void dispose() {
    _easyPermission.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ElevatedButton(
                child: Text("检查权限"),
                onPressed: () {
                  FlutterEasyPermission.has(perms: permissions, permsGroup: permissionGroup).then(
                    (value) => value
                      ? debugPrint("已获得授权")
                      : debugPrint("未获得授权")
                  );
                },
              ),
              ElevatedButton(
                child: Text("请求权限"),
                onPressed: () {
                  FlutterEasyPermission.request(
                    perms: permissions,
                    permsGroup: permissionGroup,
                    rationale: "测试需要这些权限"
                  );
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}

参考

希望这篇文档对你有所帮助!如果你有任何问题或建议,请随时提出。


更多关于Flutter权限管理插件flutter_easy_permission的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter权限管理插件flutter_easy_permission的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用flutter_easy_permission插件进行权限管理的代码示例。这个插件可以帮助你简化Android和iOS上的权限请求流程。

首先,确保你已经在pubspec.yaml文件中添加了flutter_easy_permission依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_easy_permission: ^3.0.0  # 请使用最新版本

然后,运行flutter pub get来安装依赖。

接下来,在你的Flutter项目中,你可以按照以下步骤使用flutter_easy_permission

  1. 导入插件

在你的Dart文件中导入插件:

import 'package:flutter_easy_permission/flutter_easy_permission.dart';
  1. 检查并请求权限

你可以使用FlutterEasyPermission类来检查权限状态并请求权限。下面是一个示例,展示如何请求存储权限:

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    // 检查存储权限
    _checkStoragePermission();
  }

  Future<void> _checkStoragePermission() async {
    // 检查存储权限状态
    var status = await FlutterEasyPermission.checkPermission(Permission.storage);

    if (status == PermissionStatus.granted) {
      // 权限已授予,执行相关操作
      print("Storage permission is granted.");
    } else if (status == PermissionStatus.denied || status == PermissionStatus.permanentlyDenied) {
      // 请求存储权限
      var result = await FlutterEasyPermission.requestPermission(Permission.storage);

      if (result == PermissionStatus.granted) {
        // 权限请求成功
        print("Storage permission is requested and granted.");
      } else if (result == PermissionStatus.denied || result == PermissionStatus.permanentlyDenied) {
        // 权限请求被拒绝
        print("Storage permission is denied.");
        // 如果权限被永久拒绝,可以引导用户到设置页面手动开启
        if (result == PermissionStatus.permanentlyDenied) {
          // 打开应用设置页面(仅限Android)
          FlutterEasyPermission.openAppSettings();
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Easy Permission Example'),
        ),
        body: Center(
          child: Text('Check console for permission status.'),
        ),
      ),
    );
  }
}
  1. 处理多个权限

如果需要同时请求多个权限,可以使用FlutterEasyPermission.requestPermissions方法。例如,请求存储和相机权限:

Future<void> _checkMultiplePermissions() async {
  var statuses = await FlutterEasyPermission.checkPermissions([Permission.storage, Permission.camera]);

  bool needRequest = false;
  List<Permission> permissionsToRequest = [];

  for (var status in statuses.entries) {
    if (status.value == PermissionStatus.denied || status.value == PermissionStatus.permanentlyDenied) {
      needRequest = true;
      permissionsToRequest.add(status.key);
    }
  }

  if (needRequest) {
    var results = await FlutterEasyPermission.requestPermissions(permissionsToRequest);

    for (var result in results.entries) {
      if (result.value == PermissionStatus.granted) {
        print("${result.key.name} permission is granted.");
      } else if (result.value == PermissionStatus.denied || result.value == PermissionStatus.permanentlyDenied) {
        print("${result.key.name} permission is denied.");
        if (result.value == PermissionStatus.permanentlyDenied) {
          FlutterEasyPermission.openAppSettings();
        }
      }
    }
  }
}

initState中调用_checkMultiplePermissions即可:

@override
void initState() {
  super.initState();
  _checkMultiplePermissions();
}

这样,你就可以在Flutter应用中轻松地使用flutter_easy_permission插件进行权限管理了。

回到顶部