getImageFile method
Returns a resized image file to fit within maxHeight and maxWidth. It tries to keep the aspect ratio. It stores the resized image by adding the size to the key or url. For example when resizing https://via.placeholder.com/150 to max width 100 and height 75 it will store it with cacheKey resized_w100_h75_https://via.placeholder.com/150.
When the resized file is not found in the cache the original is fetched from the cache or online and stored in the cache. Then it is resized and returned to the caller.
Implementation
Stream<FileResponse> getImageFile(
String url, {
String? key,
Map<String, String>? headers,
bool withProgress = false,
int? maxHeight,
int? maxWidth,
}) async* {
/// 无需验证缓存图片宽高
// if (maxHeight == null && maxWidth == null) {
// yield* getFileStream(url, key: key, headers: headers, withProgress: withProgress);
// return;
// }
/// 使用图片地址Path作为缓存key
key ??= Uri.parse(url).path;
var resizedKey = 'resized';
if (maxWidth != null) resizedKey += '_w$maxWidth';
if (maxHeight != null) resizedKey += '_h$maxHeight';
resizedKey += '_$key';
var fromCache = await getFileFromCache(resizedKey);
if (fromCache != null) {
yield fromCache;
if (fromCache.validTill.isAfter(DateTime.now())) {
return;
}
withProgress = false;
}
var runningResize = _runningResizes[resizedKey];
if (runningResize == null) {
runningResize = _fetchedResizedFile(
url,
key,
resizedKey,
headers,
withProgress,
maxWidth: maxWidth,
maxHeight: maxHeight,
).asBroadcastStream();
_runningResizes[resizedKey] = runningResize;
}
yield* runningResize;
_runningResizes.remove(resizedKey);
}