Flutter|Flutter 计算App应用缓存及清除应用缓存

整体思路

  • 通过 path_provider插件获取getTemporaryDirectory路径
  • 循环计算文件的大小(递归)
  • 递归方式删除目录
  • 计算大小
  • 渲染
1.计算App应用缓存
import 'dart:io'; import 'package:path_provider/path_provider.dart'; // 加载缓存 Future loadCache() async { Directory tempDir = await getTemporaryDirectory(); double value = https://www.it610.com/article/await _getTotalSizeOfFilesInDir(tempDir); /*tempDir.list(followLinks: false,recursive: true).listen((file){ //打印每个缓存文件的路径 print(file.path); }); */ print('临时目录大小: ' + value.toString()); return_renderSize(value); }// 循环计算文件的大小(递归) Future _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 children = file.listSync(); double total = 0; if (children != null) for (final FileSystemEntity child in children) total += await _getTotalSizeOfFilesInDir(child); return total; } return 0; } // 递归方式删除目录 Future _delDir(FileSystemEntity file) async { if (file is Directory) { final List children = file.listSync(); for (final FileSystemEntity child in children) { await _delDir(child); } } await file.delete(); } // 计算大小 _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 = https://www.it610.com/article/value / 1024; } String size = value.toStringAsFixed(2); if (size =='0.00'){ return '0M'; } // print('size:${size == 0}\n ==SIZE${size}'); return size + unitArr[index]; }

2.清除App缓存
/// 清理缓存 /// void _clearCache() async { Directory tempDir = await getTemporaryDirectory(); //删除缓存目录 await _delDir(tempDir); await loadCache(); Toast.show('清除缓存成功'); }

3.渲染文字(使用)
String _cacheSizeStr = '0'; @override void initState() { // TODO: implement initState super.initState(); getCount(); } void getCount() async{ _cacheSizeStr= await loadCache(); print('===cacheSize大小:${_cacheSizeStr}'); setState(() {}); }

补充 1.清理和获取图片缓存
/// 清理内存: //clear all of imagein memory void clearMemoryImageCache() { PaintingBinding.instance.imageCache.clear(); }// get ImageCache void getMemoryImageCache() { PaintingBinding.instance.imageCache; }

注意:
【Flutter|Flutter 计算App应用缓存及清除应用缓存】Future 要想获取其中的内容,前面必须+await 才可以,否则会报错

    推荐阅读