loadFromDiskCache method
Load the disk cache
Check the following conditions: (no CacheRule)
- Check if cache directory exist. If not exist, create it.
- Check if cached file(uid) exist. If yes, load the cache, otherwise go to download step.
Implementation
Future<Uint8List?> loadFromDiskCache() async {
AdvancedNetworkImage key = this;
String uId = uid(key.url);
if (key.cacheRule == null) {
Directory _cacheImagesDirectory =
Directory(join((await getTemporaryDirectory()).path, 'imagecache'));
if (_cacheImagesDirectory.existsSync()) {
File _cacheImageFile = File(join(_cacheImagesDirectory.path, uId));
if (_cacheImageFile.existsSync()) {
if (key.loadedFromDiskCacheCallback != null)
key.loadedFromDiskCacheCallback!();
return await _cacheImageFile.readAsBytes();
}
} else {
await _cacheImagesDirectory.create();
}
Uint8List? imageData = await loadFromRemote(
key.url,
key.header,
key.retryLimit,
key.retryDuration,
key.retryDurationFactor,
key.timeoutDuration,
key.loadingProgress,
key.getRealUrl,
skipRetryStatusCode: key.skipRetryStatusCode,
printError: key.printError,
);
if (imageData != null) {
if (key.preProcessing != null)
imageData = (await key.preProcessing!(imageData)) ?? imageData;
await (File(join(_cacheImagesDirectory.path, uId)))
.writeAsBytes(imageData);
return imageData;
}
} else {
DiskCache diskCache = DiskCache()..printError = key.printError;
Uint8List? data = await diskCache.load(uId, rule: key.cacheRule);
if (data != null) {
if (key.loadedFromDiskCacheCallback != null)
key.loadedFromDiskCacheCallback!();
return data;
}
data = await loadFromRemote(
key.url,
key.header,
key.retryLimit,
key.retryDuration,
key.retryDurationFactor,
key.timeoutDuration,
key.loadingProgress,
key.getRealUrl,
printError: key.printError,
);
if (data != null) {
if (key.preProcessing != null)
data = (await key.preProcessing!(data)) ?? data;
await diskCache.save(uId, data, key.cacheRule!);
return data;
}
}
return null;
}