Flutter 中缓存大小的最大限制

3
我正在使用Firestore作为数据库,并在我的Flutter应用程序(iOS和Android)中使用cached_network_image来加载和缓存图像。我注意到,在调试模式下运行一段时间后,应用程序的缓存大小会变得太大(+300 mb)。 在Flutter中,应用程序使用的缓存大小是否有最大限制? 是否有一种方法可以强制设置缓存大小的限制,以便每当缓存大小达到其最大限制时,就会删除最旧的缓存文件?
3个回答

2

cached_network_image 依赖于 flutter_cache_manager

CacheManager 可以下载并缓存应用程序缓存目录中的文件。可以更改有关保留文件时间的各种设置。

工作原理

默认情况下,缓存文件存储在应用程序的临时目录中。这意味着操作系统随时可以删除这些文件。

使用 sqflite 存储有关文件的信息的数据库。数据库的文件名是 cacheManager 的键,因此必须是唯一的。

此缓存信息包含文件有效的截止日期和与 http 缓存控制一起使用的 eTag。

方法

removeFile 从缓存中删除文件。

emptyCache 删除缓存中的所有文件。

示例

void _clearCache() {
    DefaultCacheManager().emptyCache();
    
  }

如果您希望能够在一段时间后删除图像,则需要实现自定义缓存,以在给定的天数后删除图像。

来自文档 TL:DR

class CustomCacheManager extends BaseCacheManager {
  static const key = "customCache";

  static CustomCacheManager _instance;

  factory CustomCacheManager() {
    if (_instance == null) {
      _instance = new CustomCacheManager._();
    }
    return _instance;
  }

  CustomCacheManager._() : super(key,
      maxAgeCacheObject: Duration(days: 7),
      maxNrOfCacheObjects: 20);

  Future<String> getFilePath() async {
    var directory = await getTemporaryDirectory();
    return p.join(directory.path, key);
  }

1
图像缓存可以缓存高达1000张图片高达100 MB。这可能更多,但最小为100 MB。

你有任何来源吗? - Donki
1
https://api.flutter.dev/flutter/painting/ImageCache-class.html - akash maurya

0
对于你的用例,可以使用extended_image来缓存图像,并使用clearDiskCachedImages方法清除缓存。
// Clear the disk cache directory then return if it succeed.
///  <param name="duration">timespan to compute whether file has expired or not</param>
Future<bool> clearDiskCachedImages({Duration duration})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接