Flutter清除本地文件缓存

4,121 阅读1分钟

文章转载自这里

1.思路:

Flutter 获取应用缓存需要借助于path_provider插件。 path_provider 是一个用于查找文件系统上常用位置的Flutter插件。用来获取 Android 和 iOS 的缓存文件夹,然后再根据文件循环计算出缓存文件的大小。

2.path_provider介绍:

1、getTemporaryDirectory() ///< 在iOS上,对应NSTemporaryDirectory();在Android上,对应getCacheDir。

2、getApplicationDocumentsDirectory() ///< 在iOS上,对应NSDocumentsDirectory;在Android上,对应AppData目录。

3、getExternalStorageDirectory() ///< 在iOS上,抛出异常,在Android上,对应getExternalStorageDirectory

3.实践:

1.导入包:

import 'package:path_provider/path_provider.dart';
import 'dart:io';

2.获取缓存:

/// 获取缓存
Future<double> loadApplicationCache() async {
  /// 获取文件夹
  Directory directory = await getApplicationDocumentsDirectory();
  /// 获取缓存大小
  double value = await getTotalSizeOfFilesInDir(directory);
  return value;
}

/// 循环计算文件的大小(递归)
Future<double> getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
  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;
}

/// 缓存大小格式转换
String formatSize(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];
}

3.清除缓存:

/// 删除缓存
void clearApplicationCache() async {
  Directory directory = await getApplicationDocumentsDirectory();
  //删除缓存目录
  await deleteDirectory(directory);
}

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

4.测试上面的方法:

...
// 获取缓存
onPressed: () async {
  double value = await cacheManage.loadApplicationCache();
  String str = cacheManage.formatSize(value);
  print('获取app缓存: ' + str);
},
...
// 删除缓存
onPressed: (){
  cacheManage.clearApplicationCache();
  print('删除缓存');
},
...

5.打印出的结果:

I/flutter (10920): 获取app缓存: 12.00B
I/flutter (10920): 删除缓存
I/flutter (10920): 获取app缓存: 0.00B