Flutter中如何获取应用程序缓存大小?

Vip*_*egi 9 dart flutter

我的应用程序是基于图像的,我使用CachedNetworkImage来处理来自网络的图像。我想向用户展示设备上缓存的图像大小以及在应用程序中清理的选项。我可以使用flutter_cache_manager清理应用程序的缓存。

清理应用程序缓存:

await DefaultCacheManager().emptyCache();
Run Code Online (Sandbox Code Playgroud)

没有这样的函数来获取应用程序的缓存大小。我怎样才能得到它?

Arb*_*ikh 6

您可以使用 dart:io 包来获取应用程序的缓存大小:

import 'dart:io';

Future<int> getCacheSize() async {
  Directory tempDir = await getTemporaryDirectory();
  int tempDirSize = _getSize(tempDir);
  return tempDirSize;
}

int _getSize(FileSystemEntity file) {
  if (file is File) {
    return file.lengthSync();
  } else if (file is Directory) {
    int sum = 0;
    List<FileSystemEntity> children = file.listSync();
    for (FileSystemEntity child in children) {
      sum += _getSize(child);
    }
    return sum;
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)