file_size_calculator_util.dart 948 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import 'package:flutter/cupertino.dart';
  2. import 'package:wechat_assets_picker/wechat_assets_picker.dart';
  3. import 'package:photo_manager/photo_manager.dart';
  4. class FileSizeCalculatorUtil {
  5. static final Map<String, double> fileSizeCache = {};
  6. /// 获取文件大小
  7. static Future<double> getFileSize(String assetId) async {
  8. if (fileSizeCache.containsKey(assetId)) {
  9. return fileSizeCache[assetId]!;
  10. }
  11. final entity = await AssetEntity.fromId(assetId);
  12. if (entity == null) return 0;
  13. final file = await entity.file;
  14. if (file == null) return 0;
  15. double size = (await file.length()) / 1024;
  16. if ( await file.exists()) {
  17. try {
  18. await file.delete();
  19. } catch (e) {
  20. debugPrint("Delete file error: $e");
  21. }
  22. } else {
  23. debugPrint("File not exists: ${file.path}");
  24. }
  25. if (size <= 0) {
  26. return 0;
  27. }
  28. fileSizeCache[assetId] = size;
  29. return size;
  30. }
  31. }