Flutter 清除应用缓存

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

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

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

定义缓存管理类

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

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

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

/// 缓存管理类
/// ./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);
  }
}
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值