You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter如何删除目录内除.db后缀外文件及获取缓存目录大小

缓存目录文件清理方案

1. 仅保留.db后缀文件的删除实现

原有代码直接对整个目录执行递归删除,会清空目录本身及所有内容,不符合需求。正确实现逻辑为遍历目录下所有文件,仅删除后缀不为.db的文件,代码示例如下:

import 'dart:io';

/// 清理指定目录下除.db后缀之外的所有文件
/// [dirPath] 目标缓存目录路径
/// [recursive] 是否递归处理子目录,默认true
void cleanCacheExcludeDb(String dirPath, {bool recursive = true}) {
  final targetDir = Directory(dirPath);
  if (!targetDir.existsSync()) return;

  targetDir.listSync(recursive: recursive).forEach((entity) {
    // 仅处理文件,避免删除目录结构
    if (entity is File && !entity.path.endsWith('.db')) {
      entity.deleteSync();
    }
  });

  // 如需同时删除空的子目录,可添加以下逻辑
  if (recursive) {
    targetDir.listSync(recursive: true).whereType<Directory>().forEach((dir) {
      if (dir.listSync().isEmpty) {
        dir.deleteSync();
      }
    });
  }
}

2. Flutter获取缓存目录大小实现

需要先通过path_provider依赖获取应用缓存目录路径,再遍历所有文件累加大小,代码示例如下:

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

/// 获取应用缓存目录总大小,单位为字节
Future<int> getTotalCacheSize() async {
  final cacheDir = await getTemporaryDirectory();
  if (!cacheDir.existsSync()) return 0;

  int totalBytes = 0;
  cacheDir.listSync(recursive: true).forEach((entity) {
    if (entity is File) {
      totalBytes += entity.lengthSync();
    }
  });
  return totalBytes;
}

/// 工具方法:将字节数转换为人类可读的大小格式
String formatSize(int bytes) {
  const units = ['B', 'KB', 'MB', 'GB'];
  int index = 0;
  double size = bytes.toDouble();
  while (size >= 1024 && index < units.length - 1) {
    size /= 1024;
    index++;
  }
  return '${size.toStringAsFixed(1)}${units[index]}';
}

调用示例:

int cacheBytes = await getTotalCacheSize();
String readableSize = formatSize(cacheBytes); // 输出示例:24.3MB

内容的提问来源于stack exchange,提问作者LearnToday

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 04:18:03