image_picker_util.dart 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import 'dart:io';
  2. import 'package:flutter/cupertino.dart';
  3. import 'package:wechat_assets_picker/wechat_assets_picker.dart';
  4. import '../resource/colors.gen.dart';
  5. import '../resource/string.gen.dart';
  6. /// 本地选择图片工具类
  7. class ImagePickerUtil {
  8. static final Color _themeColor = ColorName.colorBrand;
  9. /// 选择图片
  10. static Future<List<AssetEntity>> pickImage(
  11. BuildContext context, {
  12. required int maxAssetsCount,
  13. List<AssetEntity> selectedAssets = const [],
  14. }) async {
  15. return await AssetPicker.pickAssets(
  16. context,
  17. pickerConfig: AssetPickerConfig(
  18. // 最大选择数量
  19. maxAssets: maxAssetsCount,
  20. // 已选择的图片列表
  21. selectedAssets: selectedAssets,
  22. // 自定义按钮文字
  23. textDelegate: const CustomChineseDelegate(),
  24. // 主题
  25. pickerTheme: AssetPicker.themeData(
  26. // 主题色
  27. _themeColor,
  28. // 深色默认
  29. light: false,
  30. ),
  31. // 设置为不能预览的模式
  32. specialPickerType: SpecialPickerType.noPreview,
  33. // 只能选取图片类型
  34. requestType: RequestType.image,
  35. // 关闭拽托选择
  36. dragToSelect: false,
  37. // 实现最近相册的名字显示
  38. pathNameBuilder:
  39. (AssetPathEntity path) => switch (path) {
  40. final p when p.isAll => StringName.recently,
  41. _ => path.name,
  42. },
  43. ),
  44. ) ??
  45. [];
  46. }
  47. /// 跳转到图片预览
  48. static Future<List<AssetEntity>> goImagePreview(
  49. BuildContext context,
  50. List<AssetEntity> previewAssets,
  51. int index,
  52. ) async {
  53. final List<AssetEntity> result =
  54. await AssetPickerViewer.pushToViewer(
  55. context,
  56. // 当前预览的索引位置
  57. currentIndex: index,
  58. // 资源列表
  59. previewAssets: previewAssets,
  60. // 主题色
  61. themeData: AssetPicker.themeData(_themeColor),
  62. ) ??
  63. [];
  64. return result;
  65. }
  66. /// AssetEntity实体,转换为File列表
  67. /// [assetsList] 图片、视频选择后的资源列表
  68. static Future<List<File>> convertAssetToFile(
  69. List<AssetEntity> assetsList,
  70. ) async {
  71. List<File> files = [];
  72. for (var asset in assetsList) {
  73. final file = await asset.file;
  74. if (file != null) {
  75. files.add(file);
  76. }
  77. }
  78. return files;
  79. }
  80. }
  81. /// 自定义按钮文字
  82. class CustomChineseDelegate extends AssetPickerTextDelegate {
  83. const CustomChineseDelegate();
  84. @override
  85. String get confirm => StringName.nextStep;
  86. }