getFile method

Future<File?> getFile(
  1. String url, {
  2. Duration? ttl,
  3. bool forceRefresh = false,
})

Fetches the file corresponding to url from the local cache or over the network.

Concurrency deduplication: shares in-flight Future instances for identical concurrent URL requests (unless forceRefresh is true) to prevent duplicate downloads and concurrent write race conditions.

If ttl is provided and the local file was modified within ttl, the cached file is returned immediately without contacting the remote server.

Otherwise, an HTTP request is made:

  • Sends If-None-Match (ETag) and If-Modified-Since from metadata or file.
  • On 304 Not Modified, metadata headers are updated and the existing file is returned.
  • On 200 OK, bytes and response headers are atomically written to disk.
  • On network errors or unexpected status codes, the existing cached file is returned as a graceful offline fallback if available.

Implementation

Future<File?> getFile(
  String url, {
  Duration? ttl,
  bool forceRefresh = false,
}) {
  final trimmedUrl = url.trim();
  if (trimmedUrl.isEmpty) return Future.value(null);

  // Reuse in-flight request if identical URL is currently being fetched.
  if (!forceRefresh) {
    final inFlight = _inFlightRequests[trimmedUrl];
    if (inFlight != null) return inFlight;
  }

  final future = _fetchFile(trimmedUrl, ttl: ttl, forceRefresh: forceRefresh);
  _inFlightRequests[trimmedUrl] = future;

  return future.whenComplete(() {
    _inFlightRequests.remove(trimmedUrl);
  });
}