Flutter中Cached Network Image缓存Firestore图片的自动清理机制及配置咨询
Flutter中Cached Network Image缓存Firestore图片的自动清理机制及配置咨询
嘿,我来帮你理清Cached Network Image的缓存逻辑哈!
首先说默认情况:Cached Network Image 默认不会按时间自动清理缓存,它依赖的flutter_cache_manager包默认的策略是「当缓存目录占用空间超过上限时,按LRU(最近最少使用)规则删除旧缓存」,而不是按时间过期。
默认的缓存上限是100MB,单个缓存文件最大2MB。当缓存总大小超过100MB时,会自动删除最近最少被访问的文件,直到缓存回到约80MB的大小。
如果你的需求是让缓存按时间自动过期清理,那需要自定义CacheManager来配置过期规则,具体步骤如下:
自定义缓存管理器类,设置缓存过期时间
创建一个继承自CacheManager的类,在Config里指定stalePeriod(缓存过期时长),比如设置7天过期:import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:path_provider/path_provider.dart'; class CustomFirestoreCacheManager extends CacheManager { static const _cacheKey = 'firestore_image_cache'; static CustomFirestoreCacheManager? _instance; factory CustomFirestoreCacheManager() { _instance ??= CustomFirestoreCacheManager._(); return _instance!; } CustomFirestoreCacheManager._() : super( Config( _cacheKey, stalePeriod: const Duration(days: 7), // 设置7天后缓存过期 maxCacheSize: 100 * 1024 * 1024, // 保持100MB的缓存上限 maxCacheObjectSize: 2 * 1024 * 1024, // 单个图片最大2MB ), ); }在使用
CachedNetworkImage时指定自定义缓存管理器
替换默认的缓存管理器为你自定义的类,这样所有Firestore图片都会使用这个带时间过期规则的缓存策略:CachedNetworkImage( imageUrl: '你的Firestore图片URL', cacheManager: CustomFirestoreCacheManager(), placeholder: (context, url) => const CircularProgressIndicator(), errorWidget: (context, url, error) => const Icon(Icons.error_outline), )
补充说明几点:
stalePeriod的作用是标记「超过这个时间未被访问的缓存文件」为过期,清理操作会在缓存写入或访问时触发,不是后台定时任务哦。- 如果需要手动清理缓存,可以调用这些方法:
CustomFirestoreCacheManager().emptyCache():清空所有缓存CustomFirestoreCacheManager().removeFile('图片URL'):删除单个指定图片的缓存
备注:内容来源于stack exchange,提问作者Rkdio
相关产品推荐
相关产品推荐

