Flutter Cache Manager
Cache Library
Flutter Cache Manager
Overview
Flutter Cache Manager is a generic cache manager for Flutter applications that saves web files on device storage and manages cache information using SQLite. It's an essential tool enabling efficient and reliable caching implementation in Flutter applications.
Details
Flutter Cache Manager efficiently retrieves files using Cache-Control HTTP headers and determines when to delete files using two variables: maxNrOfCacheObjects and stalePeriod. When a file is in the cache, it's always directly returned when calling getSingleFile or getFileStream. After that, the information is checked to see if the file is actually still valid. If the file is outdated according to the Cache-Control headers, the manager tries to update the file and store the new one in the cache.
Cache cleaning happens continuously - when there are too many objects, files are deleted ordered by last use, and files that haven't been used for longer than the stale period are also removed. The thread-safe implementation allows safe usage from multiple goroutines.
Pros and Cons
Pros
- Automatic Cache-Control HTTP header processing
- File validity checking and background updates
- SQLite-based persistent cache information management
- Configurable cache size and expiration settings
- File save/load functionality (c.Items() and NewFrom())
- Thread-safe design supporting concurrent access
- Optimal for caching images, videos, and other network resources
Cons
- Creating multiple CacheManager instances with the same key causes conflicts
- Limited compatibility with other cache systems due to no network serialization requirement
- Flutter/Dart exclusive, not usable on other platforms
- Storage usage needs attention when caching large amounts of files
Reference Links
Code Examples
Basic Setup
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
// Using DefaultCacheManager
final cacheManager = DefaultCacheManager();
// Get single file
File file = await cacheManager.getSingleFile(url);
// Get file stream (cached first, then download)
Stream<FileResponse> fileStream = cacheManager.getFileStream(url);
Custom Cache Manager Creation
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
class CustomCacheManager {
static const key = 'customCacheKey';
static CacheManager instance = CacheManager(
Config(
key,
stalePeriod: const Duration(days: 7),
maxNrOfCacheObjects: 100,
repo: JsonCacheInfoRepository(databaseName: key),
fileService: HttpFileService(),
),
);
}
// Usage example
File file = await CustomCacheManager.instance.getSingleFile(url);
Cached File Removal
// Remove cache for specific URL
await cacheManager.removeFile(url);
// Clear all cache
await cacheManager.emptyCache();
// Remove only expired files
await cacheManager.cleanUp();
File Information Checking
// Get file info from cache
FileInfo? fileInfo = await cacheManager.getFileFromCache(url);
if (fileInfo != null) {
print('File path: ${fileInfo.file.path}');
print('Valid until: ${fileInfo.validTill}');
print('Original URL: ${fileInfo.originalUrl}');
}
Download with Progress
Stream<FileResponse> stream = cacheManager.getFileStream(
url,
headers: {'Authorization': 'Bearer token'},
);
await for (FileResponse response in stream) {
if (response is DownloadProgress) {
print('Download progress: ${response.downloaded} / ${response.totalSize}');
} else if (response is FileInfo) {
print('File retrieval complete: ${response.file.path}');
}
}
Caching with Expiration
// Cache file with specific expiration
File file = await cacheManager.getSingleFile(
url,
headers: {'Cache-Control': 'max-age=3600'}, // 1 hour
);
// Set global expiration in cache manager config
CacheManager(
Config(
'myCache',
stalePeriod: const Duration(hours: 1),
maxNrOfCacheObjects: 50,
),
);