清除应用缓存是 APP 常用的功能之一。清除缓一般只有 2 个操作:

  • 获取缓存大小
  • 清除缓存数据

本文通过实现一个缓存管理类,来操作应用缓存。

定义缓存管理类

缓存管理类,是一个简单的缓存管理封装,他通过几个接口共 APP 组件使用。

该类需要使用到以下依赖:

  • path_provider:获取目录;

首先建立缓存管理类,并规划好一个大纲:

/// 缓存管理类
/// ./lib/utils/cache_util.dart
class CacheUtil {/// 获取缓存大小static Future<int> total() async {}/// 清除缓存static Future<int> clear() async {}/// 递归缓存目录,计算缓存大小static Future<int> _reduce() async {}/// 递归删除缓存目录和文件static Future<int> _delete() async {}
}

获取缓存大小

获取缓存大小,需要递归处理计算缓存目录下的文件大小。

/// 获取缓存大小
static Future<int> total() async {Directory tempDir = await getTemporaryDirectory();if (tempDir == null) return 0;int total = await _reduce(tempDir);return total;
}

递归计算缓存目录:

/// 递归缓存目录,计算缓存大小
static Future<int> _reduce(final FileSystemEntity file) async {/// 如果是一个文件,则直接返回文件大小if (file is File) {int length = await file.length();return length;}/// 如果是目录,则遍历目录并累计大小if (file is Directory) {final List<FileSystemEntity> children = file.listSync();int total = 0;if (children != null && children.isNotEmpty)for (final FileSystemEntity child in children)total += await _reduce(child);return total;}return 0;
}

清除缓存

和递归获取缓存目录下的文件大小类似,清除缓存就是遍历删除缓存目录下的文件:

/// 清除缓存
static Future<void> clear() async {Directory tempDir = await getTemporaryDirectory();if (tempDir == null) return;await _delete(tempDir);
}

递归清除缓存目录:

/// 递归删除缓存目录和文件
static Future<void> _delete(FileSystemEntity file) async {if (file is Directory) {final List<FileSystemEntity> children = file.listSync();for (final FileSystemEntity child in children) {await _delete(child);}} else {await file.delete();}
}

完整代码

完整代码如下:

import 'dart:io';
import 'package:path_provider/path_provider.dart';/// 缓存管理类
/// ./lib/utils/cache_util.dart
class CacheUtil {/// 获取缓存大小static Future<int> total() async {Directory tempDir = await getTemporaryDirectory();if (tempDir == null) return 0;int total = await _reduce(tempDir);return total;}/// 清除缓存static Future<void> clear() async {Directory tempDir = await getTemporaryDirectory();if (tempDir == null) return;await _delete(tempDir);}/// 递归缓存目录,计算缓存大小static Future<int> _reduce(final FileSystemEntity file) async {/// 如果是一个文件,则直接返回文件大小if (file is File) {int length = await file.length();return length;}/// 如果是目录,则遍历目录并累计大小if (file is Directory) {final List<FileSystemEntity> children = file.listSync();int total = 0;if (children != null && children.isNotEmpty)for (final FileSystemEntity child in children)total += await _reduce(child);return total;}return 0;}/// 递归删除缓存目录和文件static Future<void> _delete(FileSystemEntity file) async {if (file is Directory) {final List<FileSystemEntity> children = file.listSync();for (final FileSystemEntity child in children) {await _delete(child);}} else {await file.delete();}}
}

应用实战

实战中,我们添加 filesize 依赖用来友好显示文件尺寸。使用 ValueNotifierValueListenableBuilder 更新界面。实现过程如下:

  • 定义一个 cacheSizeValueNotifier<int> cacheSize = ValueNotifier(0);
  • 定义一个 initCache 异步方法,用来刷新缓存,在 initStat 和 清除缓存 时调用,已实现实时刷新。
  • 定义一个 清除缓存 的方法,用来调用清除缓存和刷新缓存。

Simulator Screen Shot - iPhone 11 - 2021-03-27 at 13.06.05.png

缓存展示组件

ValueListenableBuilder(valueListenable: cacheSize,builder: (BuildContext context, int size, Widget _) {return Tile(title: Text('本地缓存'),titleSub: Text('点击清除缓存,但不会清除已下载的歌曲'),detail: size != null && size > 0 ? filesize(size) : '',action: SizedBox(width: 16),onPressed: handleClearCache,);},
)

初始化缓存方法

Future<void> initCache() async {/// 获取缓存大小int size = await CacheUtil.total();/// 复制变量cacheSize.value = size ?? 0;
}

清除缓存方法

Future<void> handleClearCache() async {try {if (cacheSize.value <= 0) throw '没有缓存可清理';/// 给予适当的提示/// bool confirm = await showDialog();/// if (confirm != true) return;/// 执行清除缓存await CacheUtil.clear();/// 更新缓存await initCache();AppUtil.showToast('缓存清除成功');} catch (e) {AppUtil.showToast(e);}
}

Flutter 清除应用缓存相关推荐

  1. 清除Squid缓存的小工具

    [ 2007-11-2 17:49 | by 张宴 ] 以前我写过一篇<清除指定squid缓存文件的脚本>,但在取URL时存在10%的错误率.如今找到一款老外的程序,可以批量清除某类URL ...

  2. vue 删除页面缓存_vue项目强制清除页面缓存的例子

    异常描述: 支付宝中内嵌h5项目(vue框架开发),前端重新打包上传之后访问页面会导致页面空白.页面tab点击异常之类异常情况,需要手动清除支付宝缓存才可以正常访问. 解决方案: 在HTTP协议中,只 ...

  3. ASP.NET清除页面缓存的方法

    ASP.NET清除页面缓存 (1)   Response.Buffer = true;              Response.ExpiresAbsolute = System.DateTime. ...

  4. npm 安装包失败 --- 清除npm缓存

    今天同事给了一个webpack的项目,我拿过来,npm  install 突然出现报错了,并且报了一个奇怪的错误, 如下所示, Unexpected end of JSON input while p ...

  5. 15、如何在Linux和Windows下清除DNS缓存

    由于各种原因,您可能需要刷新或清除Linux系统上的本地DNS缓存. 如何清除/刷新Linux下的DNS缓存 默认情况下,操作系统级别没有安装或启用DNS缓存,但如果安装了下面列出的任何缓存服务,请使 ...

  6. java 监听map的数据_使用监听器:定时清除map缓存的key value .

    使用监听器:定时清除map缓存的key value . 配置web.xml:注意位置 com.my.common.listener.TimerListener 监听类: public class Ti ...

  7. win7怎么清理java缓存文件夹_Win7怎么清除浏览器缓存?清除电脑缓存的妙招

    电脑使用久了之后,缓存文件也将越来越多,慢慢的你会觉得系统变得很卡,所以我们需要定期的清除缓存.而产生缓存的来源,无非就是系统和运用程序,其中应用程序就属浏览器的缓存最多了,那么Win7系统下要怎么清 ...

  8. 若依前后端分离版数据库已经存在的字典添加一条后刷新没作用,必须清除Redis缓存

    场景 使用若依的前后端分离版,前端下拉框的使用直接查询的是字典表中的数据. 对于某个类型的字典如果之前已经添加过并使用过,后来想要再添加一条此类型的字典. 在数据库中添加后,前端刷新下,发现没有获取到 ...

  9. 微信小程序开发工具 清除授权缓存/文件缓存/登录缓存等等

    今天2.19.3.25 在开发微信小程序时,作为测试号想清除授权缓存,一直没有找到方法, 最后无意中看到了解决方法 微信小程序开发工具 清除授权缓存/文件缓存/登录缓存等等.完美解决

  10. 清除webBrowser 缓存和Cookie的解决方案

    清除webBrowser 缓存和Cookie的解决方案 通过测试webBrowser与IE缓存和Cookie都存放在Local Settings\Temporary Internet Files,我们 ...

最新文章

  1. 【OpenCV】读取csv文件
  2. 有关Android的调试时候常用到的一些技巧
  3. Linux LVM卷挂载
  4. 文本编辑器创建工具栏
  5. DCMTK:测试VR类的compare()运算符
  6. 文件和内建函数 open() 、file()
  7. Flink】FLink 通讯组件 RPC
  8. Oracle数据库异常---OracleDBConsoleorcl无法启动
  9. 复购分析实践中,Pandas 遇到了大难题
  10. oracle 10g rac 停止,Oracle10g RAC 关闭及启动
  11. 解决windows update失败,正在还原的问题
  12. 交叉验证与训练集、验证集、测试集
  13. arpspoof: libnet_check_iface() ioctl: No such device 解决方法
  14. 网吧服务器哪个好稳定,网吧服务器不应盲目追高新:够用稳定就好
  15. 基于STM32的电子时钟设计
  16. android wifi 流程图_实现双wifi的方法及Android终端与流程
  17. VirtualBox虚拟机使用Vagrant连接win(甲骨文Oracle VM )
  18. 长在火山熔岩石板地上的大米
  19. 《Windows核心编程》读书笔记二十五章 未处理异常,向量化异常处理与C++异常
  20. Github 无法显示markdown图片

热门文章

  1. Visual Studio Code讲解(二) ssh远程操作电脑
  2. Mysql 笔记(二)
  3. gitee免费部署静态网站
  4. [渝粤教育] 中国科学技术大学 化学实验安全知识 参考 资料
  5. 如何理解时间复杂度和空间复杂度
  6. DANDELION 病毒
  7. CF 1056D Decorate Apple Tree
  8. react 组件 进阶之 ref (ts 版本)
  9. 【Python机器学习及实践】实战篇:泰坦尼克号罹难乘客预测
  10. SELECT list is not in GROUP BY clause and contains nonaggregated column 异常