flutter 清理缓存功能

1.

  ///加载缓存
  Future<Null> loadCache() async {
    try {
      _tempDir = await getTemporaryDirectory();
      double value = await _getTotalSizeOfFilesInDir(_tempDir);
      /*tempDir.list(followLinks: false,recursive: true).listen((file){
          //打印每个缓存文件的路径
        print(file.path);
      });*/
      print('临时目录大小: ' + value.toString());
      setState(() {
        _cacheSize = _renderSize(value);
      });
    } catch (err) {
      print(err);
    }
  }

2.

  /// 递归方式 计算文件的大小
  Future<double> _getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    try {
      if (file is File) {
        int length = await file.length();
        return double.parse(length.toString());
      }
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        double total = 0;
        if (children != null)
          for (final FileSystemEntity child in children)
            total += await _getTotalSizeOfFilesInDir(child);
        return total;
      }
      return 0;
    } catch (e) {
      print(e);
      return 0;
    }
  }

3.

 ///递归方式删除目录
  Future<Null> delDir(FileSystemEntity file) async {
    try {
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        for (final FileSystemEntity child in children) {
          await delDir(child);
        }
      }
      await file.delete();
    } catch (e) {
      print(e);
    }
  }

格式化文件大小

  ///格式化文件大小
  _renderSize(double value) {
    if (null == value) {
      return 0;
    }
    List<String> unitArr = List()..add('B')..add('K')..add('M')..add('G');
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }
Future _clearCache() async {
    //此处展示加载loading
    try {
      _tempDir = await getTemporaryDirectory();
      double value = await _getTotalSizeOfFilesInDir(_tempDir);
      print("$value");
      if (value <= 0) {
        ToastUtil.showText(context, msg: '暂无缓存');
      } else if (value >= 0) {
        var hide = ToastUtil.showLoadingText_iOS(context, msg: "正在清理中...");
        Future.delayed(Duration(seconds: 2), () async {
  //删除缓存目录
      await delDir(_tempDir);
      await loadCache();
          ToastUtil.showSuccess(context, msg: '清理完成');
          hide();
        });
      }
    
    } catch (e) {
      print(e);
      Fluttertoast.showToast(msg: '清除缓存失败');
    } finally {}
  }

 

### Flutter 打包时的缓存数据处理方法 在开发 Flutter 应用程序的过程中,缓存数据是一个常见的需求。为了确保应用程序在打包发布时能够正确管理这些缓存数据,开发者可以采用多种策略和技术手段。 #### 使用 `shared_preferences` 进行缓存数据存储 `shared_preferences` 是一种轻量级的数据持久化插件,适用于保存简单的键值对数据。通过该插件,可以在应用启动或运行期间读取和写入缓存数据[^3]。以下是具体实现方式: - **写入数据** 下面展示了如何向设备上存储不同类型的数据: ```dart import 'package:shared_preferences/shared_preferences.dart'; Future<void> saveData() async { final SharedPreferences prefs = await SharedPreferences.getInstance(); // 写入整数型数据 await prefs.setInt('counter', 10); // 写入布尔型数据 await prefs.setBool('repeat', true); // 写入浮点型数据 await prefs.setDouble('decimal', 1.5); // 写入字符串型数据 await prefs.setString('action', 'Start'); // 写入字符串列表型数据 await prefs.setStringList('items', ['Earth', 'Moon', 'Sun']); } ``` - **读取数据** 同样可以通过 `SharedPreferences` 实例调用对应的 getter 方法来获取已存储的数据: ```dart Future<void> readData() async { final SharedPreferences prefs = await SharedPreferences.getInstance(); int counter = prefs.getInt('counter') ?? 0; bool repeat = prefs.getBool('repeat') ?? false; double decimal = prefs.getDouble('decimal') ?? 0.0; String action = prefs.getString('action') ?? ''; List<String>? items = prefs.getStringList('items'); print('Counter: $counter, Repeat: $repeat, Decimal: $decimal, Action: $action, Items: $items'); } ``` #### 减少打包体积的技术方案 当涉及到优化 Flutter 应用的打包大小时,除了关注代码本身的精简外,还需要注意依赖库的选择以及构建配置文件中的设置。例如,在 Podfile 中启用 thin 模式可以帮助减少 iOS 平台下的二进制文件尺寸[^1]: ```ruby flutter 'your_flutter_project', 'x.x.x', :thin => true ``` 此外,建议定期执行清理命令以移除不必要的临时文件和旧版本资源: ```bash flutter clean ``` 对于 Android 平台,则可通过调整 Gradle 构建脚本进一步压缩 APK 文件大小。比如开启 ProGuard 或 R8 工具来进行混淆与缩减未使用的类成员操作。 #### 验证环境状态的重要性 在正式部署前务必确认本地开发工具链处于健康可用的状态下才能有效避免潜在错误发生。这一步骤通常借助于官方提供的诊断功能完成——即运行如下指令验证当前工作区是否存在异常情况[^2]: ```bash flutter doctor ``` 如果一切正常则可继续后续流程;反之需按照提示修复对应问题后再尝试重新编译项目。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值