flutter 清理缓存功能

1.

  ///加载缓存
  Future 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 _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 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 delDir(FileSystemEntity file) async {
    try {
      if (file is Directory) {
        final List 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 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)