Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions flutter_cache_manager/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
## [3.6.0] - 2026-11-14

* Adds an optional `CancellationToken` to `getFileStream`, `getSingleFile`, `downloadFile` and `ImageCacheManager.getImageFile`. Cancelling ends that call with a `CancelledException`.
* Applies cancellation per caller: callers that request the same url share one download, which stops only once every caller has cancelled. A caller without a token keeps the download running.
* Deletes the partial file of a cancelled or failed download. The previously cached file stays valid.
* Keeps `FileService.get` and `BaseCacheManager` unchanged: `HttpFileService` aborts its request on cancellation, and a custom `FileService` can read the token through `CancellationToken.current`.
* Closes the download sink when the response stream errors.

## [3.5.0] - 2026-11-04

* **DEPRECATION** Deprecates `supportedFileNames`: whether an image is resized is now decided by the image engine from the file's content instead of from the file extension derived from the `Content-Type` header of the response ([#475](https://github.com/Baseflow/flutter_cache_manager/pull/475))
Expand Down
8 changes: 8 additions & 0 deletions flutter_cache_manager/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ class CustomCacheManager {
- [How are the cache files stored?](#how-are-the-cache-files-stored)
- [When are the cached files updated?](#when-are-the-cached-files-updated)
- [When are cached files removed?](#when-are-cached-files-removed)
- [How do I cancel a download?](#how-do-i-cancel-a-download)


### How are the cache files stored?
Expand Down Expand Up @@ -113,6 +114,13 @@ The cache knows when files have been used latest. When cleaning the cache (which
deletes files when there are too many, ordered by last use, and when files just haven't been used for longer than
the stale period.

### How do I cancel a download?
Pass a `CancellationToken` to `getFileStream`, `getSingleFile`, `downloadFile` or `ImageCacheManager.getImageFile`
and call `cancel()` on it. Cancellation applies per caller: when several callers request the same url they share one
download, which only stops once every caller has cancelled, and a caller without a token keeps it running. A
cancelled download's partial file is deleted and the previously cached file stays valid. A custom `FileService`
can read the token through `CancellationToken.current` to abort its own request.


## Breaking changes in v2
- There is no longer a need to extend on BaseCacheManager, you can directly call the constructor. The BaseCacheManager
Expand Down
31 changes: 29 additions & 2 deletions flutter_cache_manager/lib/src/cache_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -65,18 +65,27 @@ class CacheManager implements BaseCacheManager {
/// When a file is cached and up to date it is return directly, when the cached
/// file is too old the file is downloaded and returned after download.
/// When a cached file is not available the newly downloaded file is returned.
/// A cancelled [cancellationToken] ends this call with a [CancelledException]
/// (see [CancellationToken]).
@override
Future<File> getSingleFile(
String url, {
String? key,
Map<String, String>? headers,
CancellationToken? cancellationToken,
}) async {
key ??= url;
cancellationToken ??= CancellationToken.current;
final cacheFile = await getFileFromCache(key);
if (cacheFile != null && cacheFile.validTill.isAfter(DateTime.now())) {
return cacheFile.file;
}
return (await downloadFile(url, key: key, authHeaders: headers)).file;
return (await downloadFile(
url,
key: key,
authHeaders: headers,
cancellationToken: cancellationToken,
)).file;
}

/// Get the file from the cache and/or online, depending on availability and age.
Expand All @@ -89,11 +98,13 @@ class CacheManager implements BaseCacheManager {
String url, {
String? key,
Map<String, String>? headers,
CancellationToken? cancellationToken,
}) {
return getFileStream(
url,
key: key,
withProgress: false,
cancellationToken: cancellationToken,
).where((r) => r is FileInfo).cast<FileInfo>();
}

Expand All @@ -114,10 +125,21 @@ class CacheManager implements BaseCacheManager {
String? key,
Map<String, String>? headers,
bool withProgress = false,
CancellationToken? cancellationToken,
}) {
key ??= url;
// Callers that only see BaseCacheManager (such as ImageCacheManager) pass
// their token through CancellationToken.runScoped.
cancellationToken ??= CancellationToken.current;
final streamController = StreamController<FileResponse>();
_pushFileToStream(streamController, url, key, headers, withProgress);
_pushFileToStream(
streamController,
url,
key,
headers,
withProgress,
cancellationToken,
);
return streamController.stream;
}

Expand All @@ -127,6 +149,7 @@ class CacheManager implements BaseCacheManager {
String? key,
Map<String, String>? headers,
bool withProgress,
CancellationToken? cancellationToken,
) async {
key ??= url;
FileInfo? cacheFile;
Expand All @@ -148,6 +171,7 @@ class CacheManager implements BaseCacheManager {
url,
key: key,
authHeaders: headers,
cancellationToken: cancellationToken,
)) {
if (response is DownloadProgress && withProgress) {
streamController.add(response);
Expand Down Expand Up @@ -185,14 +209,17 @@ class CacheManager implements BaseCacheManager {
String? key,
Map<String, String>? authHeaders,
bool force = false,
CancellationToken? cancellationToken,
}) async {
key ??= url;
cancellationToken ??= CancellationToken.current;
final fileResponse = await _webHelper
.downloadFile(
url,
key: key,
authHeaders: authHeaders,
ignoreMemCache: force,
cancellationToken: cancellationToken,
)
.firstWhere((r) => r is FileInfo);
return fileResponse as FileInfo;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_cache_manager/src/web/shared_cancellation.dart';

/// Formats that used to be recognized by the extension of the file.
///
Expand Down Expand Up @@ -36,13 +37,15 @@ mixin ImageCacheManager on BaseCacheManager {
bool withProgress = false,
int? maxHeight,
int? maxWidth,
CancellationToken? cancellationToken,
}) async* {
if (maxHeight == null && maxWidth == null) {
yield* getFileStream(
yield* _getFileStream(
url,
key: key,
headers: headers,
withProgress: withProgress,
cancellationToken: cancellationToken,
);
return;
}
Expand All @@ -60,24 +63,72 @@ mixin ImageCacheManager on BaseCacheManager {
}
withProgress = false;
}
var runningResize = _runningResizes[resizedKey];
if (runningResize == null) {
runningResize = _fetchedResizedFile(
var running = _runningResizes[resizedKey];
if (running == null) {
final cancellation = SharedCancellation();
final created = _RunningResize(
_fetchedResizedFile(
url,
key,
resizedKey,
headers,
withProgress,
cancellationToken: cancellation.token,
maxWidth: maxWidth,
maxHeight: maxHeight,
).asBroadcastStream(),
cancellation,
);
cancellation.onAllCancelled = () {
if (identical(_runningResizes[resizedKey], created)) {
_runningResizes.remove(resizedKey);
}
};
_runningResizes[resizedKey] = created;
running = created;
}
// Each caller cancels only its own view; the resize (and the download
// behind it) stops once every caller has cancelled.
try {
yield* running.cancellation.join(running.stream, cancellationToken);
} finally {
// A caller that cancelled leaves the resize to the others.
final cancelled = cancellationToken?.isCancelled ?? false;
if (!cancelled && identical(_runningResizes[resizedKey], running)) {
_runningResizes.remove(resizedKey);
}
}
}

/// [getFileStream] with [cancellationToken] applied. [BaseCacheManager]
/// does not take a token, so it is passed as [CancellationToken.current],
/// which [CacheManager] picks up.
Stream<FileResponse> _getFileStream(
String url, {
String? key,
Map<String, String>? headers,
bool withProgress = false,
CancellationToken? cancellationToken,
}) {
if (cancellationToken == null) {
return getFileStream(
url,
key,
resizedKey,
headers,
withProgress,
maxWidth: maxWidth,
maxHeight: maxHeight,
).asBroadcastStream();
_runningResizes[resizedKey] = runningResize;
key: key,
headers: headers,
withProgress: withProgress,
);
}
yield* runningResize;
_runningResizes.remove(resizedKey);
return cancellationToken.runScoped(
() => getFileStream(
url,
key: key,
headers: headers,
withProgress: withProgress,
),
);
}

final Map<String, Stream<FileResponse>> _runningResizes = {};
final Map<String, _RunningResize> _runningResizes = {};

/// Keys whose original file is known not to be resizable: it is not an
/// image the engine can decode, it is animated, or it already fits within
Expand All @@ -97,12 +148,14 @@ mixin ImageCacheManager on BaseCacheManager {
bool withProgress, {
int? maxWidth,
int? maxHeight,
CancellationToken? cancellationToken,
}) async* {
await for (final response in getFileStream(
await for (final response in _getFileStream(
url,
key: originalKey,
headers: headers,
withProgress: withProgress,
cancellationToken: cancellationToken,
)) {
if (response is DownloadProgress) {
yield response;
Expand Down Expand Up @@ -296,3 +349,10 @@ void _logResizeWarning(File file, Object error) {
CacheManagerLogLevel.warning,
);
}

class _RunningResize {
_RunningResize(this.stream, this.cancellation);

final Stream<FileResponse> stream;
final SharedCancellation cancellation;
}
97 changes: 94 additions & 3 deletions flutter_cache_manager/lib/src/web/file_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,85 @@ import 'package:http/http.dart' as http;
///Copyright (c) 2019 Rene Floor
///Released under MIT License.

/// Token that cancels a request made through a cache manager.
///
/// Pass it to [CacheManager.getFileStream], [CacheManager.getSingleFile],
/// [CacheManager.downloadFile] or `ImageCacheManager.getImageFile`.
/// Cancellation applies to that caller only: the caller's stream ends with a
/// [CancelledException], and a download shared with other callers keeps
/// running until every caller has cancelled.
///
/// While a download runs, the token that stops it is available to the
/// [FileService] as [CancellationToken.current], so a service can abort its
/// request without any change to [FileService.get]'s signature.
class CancellationToken {
bool _isCancelled = false;
Completer<void>? _completer;

static final Object _zoneKey = Object();

/// The token of the download the current [FileService.get] call belongs to,
/// or null when the request cannot be cancelled.
static CancellationToken? get current =>
Zone.current[_zoneKey] as CancellationToken?;

/// Runs [body] with this token as [current].
R runScoped<R>(R Function() body) =>
runZoned(body, zoneValues: {_zoneKey: this});

/// Whether this token has been cancelled.
bool get isCancelled => _isCancelled;

/// Cancel the request associated with this token.
void cancel() {
if (_isCancelled) return;
_isCancelled = true;
if (_completer != null && !_completer!.isCompleted) {
_completer!.complete();
}
}

/// A future that completes when this token is cancelled.
Future<void> get whenCancelled {
if (_completer == null) {
_completer = Completer<void>();
if (_isCancelled) {
_completer!.complete();
}
}
return _completer!.future;
}

/// Throws a [CancelledException] when this token has been cancelled.
void throwIfCancelled() {
if (_isCancelled) throw CancelledException();
}
}

/// Exception thrown when a request is cancelled.
class CancelledException implements Exception {
/// Creates a new [CancelledException] with an optional message.
CancelledException([this.message = 'Request was cancelled']);

/// The error message.
final String message;

@override
String toString() => 'CancelledException: $message';
}

/// Defines the interface for a file service.
/// Most common file service will be an [HttpFileService], however one can
/// also make something more specialized. For example you could fetch files
/// from other apps or from local storage.
abstract class FileService {
int concurrentFetches = 10;

/// Fetches [url], sending [headers] with the request.
///
/// When the download is cancelled by all of its callers,
/// [CancellationToken.current] is cancelled; implementations may use it to
/// abort the request. Ignoring it is safe: the response is then discarded.
Future<FileServiceResponse> get(String url, {Map<String, String>? headers});
}

Expand All @@ -32,13 +104,32 @@ class HttpFileService extends FileService {
String url, {
Map<String, String>? headers,
}) async {
final req = http.Request('GET', Uri.parse(url));
final cancellationToken = CancellationToken.current;
if (cancellationToken?.isCancelled ?? false) {
throw CancelledException();
}

final http.BaseRequest req;
if (cancellationToken != null) {
req = http.AbortableRequest(
'GET',
Uri.parse(url),
abortTrigger: cancellationToken.whenCancelled,
);
} else {
req = http.Request('GET', Uri.parse(url));
}

if (headers != null) {
req.headers.addAll(headers);
}
final httpResponse = await _httpClient.send(req);

return HttpGetResponse(httpResponse, req.url);
try {
final httpResponse = await _httpClient.send(req);
return HttpGetResponse(httpResponse, req.url);
} on http.RequestAbortedException {
throw CancelledException();
}
}
}

Expand Down
Loading
Loading