downloadImage static method

  1. @visibleForTesting
Future<Uint8List> downloadImage(
  1. String url,
  2. Duration retryDuration,
  3. Duration maxRetryDuration
)

Downloads the image

If the url is a Google Cloud Storage url, then the function get the download url. The function sends a GET requests to url and return the binary response. If there is an error in the requests, then the function retry the download after retryDuration. If the accumulated time of the retry attempts is greater than maxRetryDuration then the function returns an empty list of bytes.

Implementation

@visibleForTesting
static Future<Uint8List> downloadImage(
  String url,
  Duration retryDuration,
  Duration maxRetryDuration,
) async {
  int totalTime = 0;
  Uint8List bytes = Uint8List(0);
  Duration _retryDuration = Duration(microseconds: 1);
  if (Utils.isGsUrl(url)) url = await (_getStandardUrlFromGsUrl(url));
  while (
      totalTime <= maxRetryDuration.inSeconds && bytes.lengthInBytes <= 0) {
    await Future.delayed(_retryDuration).then((_) async {
      try {
        http.Response response = await http.get(Uri.parse(url));
        bytes = response.bodyBytes;
        if (bytes.lengthInBytes <= 0) {
          _retryDuration = retryDuration;
          totalTime += retryDuration.inSeconds;
        }
      } catch (error) {
        _retryDuration = retryDuration;
        totalTime += retryDuration.inSeconds;
      }
    });
  }
  return bytes;
}