downloadBytes function

Future<Uint8List> downloadBytes(
  1. Uri uri
)

Implementation

Future<Uint8List> downloadBytes(Uri uri) async {
  final client = http.Client();
  final request = http.Request('GET', uri);
  final response =
      await client.send(request).timeout(const Duration(seconds: 5));

  if (response.statusCode != 200) {
    throw HttpException("status code ${response.statusCode}");
  }

  List<int> bytes = [];
  double prevPercent = 0;
  await response.stream.listen((List<int> chunk) {
    bytes.addAll(chunk);

    if (response.contentLength == null) {
      debugPrint('download font: ${bytes.length} bytes');
    } else {
      final percent = ((bytes.length / response.contentLength!) * 100);
      if (percent - prevPercent > 15 || percent > 99) {
        debugPrint('download font: ${percent.toStringAsFixed(1)}%');
        prevPercent = percent;
      }
    }
  }).asFuture();

  return Uint8List.fromList(bytes);
}