getBytes method

Future<Uint8List> getBytes(
  1. String url,
  2. {Encoding storeEncoding = utf8,
  3. int? forceCache}
)

Implementation

Future<Uint8List> getBytes(
  String url, {
  Encoding storeEncoding = utf8,
  int? forceCache,
}) async {
  Completer<Uint8List> completer = Completer<Uint8List>();

  CacheEntry? entry;

  // local file cache
  entry = await load(url);
  if (entry != null && entry.isValid()) {
    completer.complete(entry.bytes);
    return completer.future;
  }

  assert(!completer.isCompleted);

  final HttpClientResponse? response = await loader(url);

  if (response == null || response.statusCode != HttpStatus.ok)
    throw Exception(
        'HTTP request failed, status code: ${response?.statusCode}, url: $url');

  final Uint8List bytes = await consolidateHttpClientResponseBytes(response);
  if (bytes.lengthInBytes == 0)
    throw Exception('NetworkImage is an empty file: $url');

  stats.bytesDownload += bytes.lengthInBytes;

  int? ttl = forceCache ?? cacheableSeconds(response);
  if (ttl != null) {
    await store(
      url,
      CacheEntry(
        url: url,
        bytes: bytes,
        ttl: ttl,
        ctime: DateTime.now(),
      ),
      encoding: storeEncoding,
    );
  } else {
    print("filecache: not cached $url");
  }
  completer.complete(bytes);

  return completer.future;
}