Bootstrap

flutter 使用wechat_assets_picker的权限检测

https://pub.dev/packages/wechat_assets_picker

AssetPicker.pickAssets之前进行权限检查

  pickImages() async {
    try {
      if (PermissionState.authorized != await AssetPicker.permissionCheck()) {
        PermissionUtil.showAllPermissions(Permission.storage, 1);
        return;
      }
      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: widget.maxAssets + 1 - saveResult.length,
          requestType: RequestType.image,
          filterOptions: FilterOptionGroup(
            imageOption: const FilterOption(
              needTitle: true,
            ),
          ),
          pageSize: 30,
          gridCount: 3,
          themeColor: Colors.black,
          specialItemBuilder: (_, entity, index) {
            return InkWell(
                onTap: () async {
                  if (!await PermissionUtil.checkAndDoDefault(
                      Permission.camera)) {
                    return;
                  }

                  final AssetEntity? entity = await CameraPicker.pickFromCamera(
                    context,
                    pickerConfig: CameraPickerConfig(
                        enableRecording: false,
                        theme: CameraPicker.themeData(
                          Colors.black,
                        )),
                    locale: const Locale('en'),
                  );
                  if (entity == null) {
                    return;
                  } else {
                    setState(() {
                      saveResult.insert(saveResult.length - 1, entity);
                    });
                    widget.change
                        ?.call(saveResult.sublist(0, saveResult.length - 1));
                    AppToast.closeBottomSheet(context);
                  }
                },
                child: SizedBox(
                  width: 33.w,
                  height: 28.h,
                  child: Icon(
                    Icons.camera_alt,
                    size: 28.w,
                    color: Colors.white,
                  ),
                ));
          },
          specialItemPosition: SpecialItemPosition.prepend,
          textDelegate: const EnglishAssetPickerTextDelegate(),
        ),
      );
      if (result != null) {
        setState(() {
          saveResult.insertAll(saveResult.length - 1, result);
        });
        widget.change?.call(saveResult.sublist(0, saveResult.length - 1));
      }
    } catch (e) {
      PermissionUtil.showAllPermissions(Permission.storage, 1);
    }
  }

permission_utils.dart

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:space_whisper_app/config.dart';
import 'package:space_whisper_app/utils/toast.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class PermissionUtil {
  static final bool isIos = Platform.isIOS;
  static final bool isAndroid = Platform.isAndroid;

  static String appName = Config.appName;

  // 检查权限 并做相应的处理
  static Future<bool> checkAndDoDefault(Permission permission) async {
    final status = await permission.status;
    if (isIos) {
      switch (status) {
        case PermissionStatus.granted:
          return true;
        case PermissionStatus.permanentlyDenied:
          // openAppSettings();
          showAllPermissions(permission, 1);
          return false;
        case PermissionStatus.denied:
        case PermissionStatus.limited:
        case PermissionStatus.restricted:
        default:
          final newStatus = await permission.request();
          if (newStatus == PermissionStatus.granted) {
            return true;
          }
          return false;
      }
    } else if (isAndroid) {
      switch (status) {
        case PermissionStatus.granted:
          return true;

        case PermissionStatus.permanentlyDenied:
          // openAppSettings();
          showAllPermissions(permission, 1);
          return false;
        // 第一次进来的时候
        case PermissionStatus.denied:
          showAllPermissions(permission, 2);
          return false;
        case PermissionStatus.limited:
        case PermissionStatus.restricted:
        default:
          final newStatus = await permission.request();
          if (newStatus == PermissionStatus.granted) {
            return true;
          }
          return false;
      }
    }
    return await permission.status == PermissionStatus.granted;
  }

  static showAllPermissions(Permission permissions, int type) {
    String title = "";
    String desc = "";
    switch (permissions.value) {
      // 相机
      case 1:
        title = "Do you authorize the '$appName' to access your camera?";
        desc =
            "Uploading an avatar requires your camera permission. We will not abuse your permission. Your camera permission is only used when you use our app to upload images.";
        break;
      // 通讯录
      case 2:
        title = "Do you authorize '$appName' to access your address book?";
        desc =
            "Access to address book friends requires your permission to access your address book. We will not abuse your permission. Your address book permissions are only used when you use our app to access your address book friends.";
        break;
      // 相册
      case 6:
        title = "Do you authorize '$appName' to access your albums?";
        desc =
            "Uploading requires your album permission. We will not abuse your permission. Your albums will only be opened if you need to use the picture function (uploading pictures, etc.).";
        break;
      // storage 权限
      case 15:
        title = "Do you authorize '$appName' to access your albums?";
        desc =
            "Uploading requires your album permission. We will not abuse your permission. Your albums will only be opened if you need to use the picture function (uploading pictures, etc.).";
        break;
      // 麦克风
      case 7:
        title = "Do you authorize '$appName' to use your microphone?";
        desc =
            "I just wanted to inform you that sending voice messages requires your microphone permission. And we promise not to abuse your microphone permission, which will be only used when you send voice messages";
        break;
    }
    AppToast.showPermissionDialog(Container(
        padding: EdgeInsets.all(20.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10.w)),
        ),
        child: Column(
          children: [
            Text(
              title,
              style: TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.bold,
                fontSize: 20.sp,
              ),
            ),
            SizedBox(
              height: 5.w,
            ),
            Text(
              desc,
              style: const TextStyle(color: Colors.black),
            ),
            SizedBox(
              height: 5.w,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                InkWell(
                  child: Container(
                    color: Colors.white,
                    padding: EdgeInsets.all(10.w),
                    child: const Text(
                      "Cancel",
                      style: TextStyle(
                        color: Color(0xFF4677FF),
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  onTap: () {
                    SmartDialog.dismiss();
                  },
                ),
                const Spacer(),
                type == 1
                    ? InkWell(
                        child: Container(
                          color: Colors.white,
                          padding: EdgeInsets.all(10.w),
                          child: const Text(
                            "Settings",
                            style: TextStyle(
                              color: Color(0xFF4677FF),
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        onTap: () {
                          SmartDialog.dismiss();
                          openAppSettings();
                        },
                      )
                    : InkWell(
                        child: Container(
                          color: Colors.white,
                          padding: EdgeInsets.all(10.w),
                          child: const Text(
                            "Confirmed",
                            style: TextStyle(
                              color: Color(0xFF4677FF),
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        onTap: () async {
                          SmartDialog.dismiss();
                          await permissions.request();
                        },
                      )
              ],
            ),
          ],
        )));
  }

  static Future<bool> checkStatusAndDoDefault(
      PermissionState status, Permission permission) async {
    if (isIos) {
      switch (status) {
        // notDetermined 未设置授权
        case PermissionState.notDetermined:
          return true;

        // 该应用程序未被授权访问照片库,用户也无法授予此类权限。
        case PermissionState.restricted:
          openAppSettings();
          return false;
        // 用户明确拒绝此应用程序访问照片库。
        case PermissionState.denied:
        // 用户明确授予此应用程序访问照片库的权限。
        case PermissionState.authorized:
        case PermissionState.limited:
        default:
          final newStatus = await permission.request();
          if (newStatus == PermissionStatus.granted) {
            return true;
          }
          return false;
      }
    } else if (isAndroid) {
      switch (status) {
        case PermissionStatus.granted:
          return true;
        default:
          final newStatus = await permission.request();
          if (newStatus == PermissionStatus.granted) {
            return true;
          } else if (newStatus == PermissionStatus.denied) {
            return false;
          } else if (newStatus == PermissionStatus.permanentlyDenied) {
            openAppSettings();
            return false;
          }
          return false;
      }
    }
    return await permission.status == PermissionStatus.granted;
  }
}

总结 核心 

使用 wechat_assets_picker 的权限检测,如果报错的情况也进行弹窗提示

PermissionUtil.showAllPermissions(Permission.storage, 1); 只是弹窗提示

    if (PermissionState.authorized != await AssetPicker.permissionCheck()) {
        PermissionUtil.showAllPermissions(Permission.storage, 1);
        return;
      }
   try {
      if (PermissionState.authorized != await AssetPicker.permissionCheck()) {
        PermissionUtil.showAllPermissions(Permission.storage, 1);
        return;
      }
    //  await AssetPicker.pickAssets(
    } catch (e) {
      PermissionUtil.showAllPermissions(Permission.storage, 1);
    }

功能二:将相机加入wechat_assets_picker

     final List<AssetEntity>? result = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: widget.maxAssets + 1 - saveResult.length,
          requestType: RequestType.image,
          filterOptions: FilterOptionGroup(
            imageOption: const FilterOption(
              needTitle: true,
            ),
          ),
          pageSize: 30,
          gridCount: 3,
          themeColor: Colors.black,
          specialItemBuilder: (_, entity, index) {
            return InkWell(
                onTap: () async {
                  if (!await PermissionUtil.checkAndDoDefault(
                      Permission.camera)) {
                    return;
                  }

                  final AssetEntity? entity = await CameraPicker.pickFromCamera(
                    context,
                    pickerConfig: CameraPickerConfig(
                        enableRecording: false,
                        theme: CameraPicker.themeData(
                          Colors.black,
                        )),
                    locale: const Locale('en'),
                  );
                  if (entity == null) {
                    return;
                  } else {
                    setState(() {
                      saveResult.insert(saveResult.length - 1, entity);
                    });
                    widget.change
                        ?.call(saveResult.sublist(0, saveResult.length - 1));
                    AppToast.closeBottomSheet(context);
                  }
                },
                child: SizedBox(
                  width: 33.w,
                  height: 28.h,
                  child: Icon(
                    Icons.camera_alt,
                    size: 28.w,
                    color: Colors.white,
                  ),
                ));
          },
          specialItemPosition: SpecialItemPosition.prepend,
          textDelegate: const EnglishAssetPickerTextDelegate(),
        ),
      );

;