fetch method

Future<Try<ByteData, NetworkException>> fetch(
  1. String url, {
  2. Method method = Method.get,
  3. Map<String, String> parameters = const {},
  4. Duration? timeout,
})

Implementation

Future<Try<ByteData, NetworkException>> fetch(String url,
    {Method method = Method.get,
    Map<String, String> parameters = const {},
    Duration? timeout}) async {
  try {
    Uri uri = Uri.parse(url);
    Uri uriWithParams = Uri(
      scheme: uri.scheme,
      userInfo: uri.userInfo,
      host: uri.host,
      port: uri.port,
      fragment: uri.fragment,
      path: uri.path,
      queryParameters: Map.of(parameters)..addAll(uri.queryParameters),
    );

    HttpClient httpClient = HttpClient();
    httpClient.connectionTimeout = timeout;
    HttpClientResponse response = await httpClient
        .openUrl(method.rawValue, uriWithParams)
        .then((request) => request.close());

    int status = response.statusCode;
    if (status >= 400) {
      return Try.failure(NetworkException(status: status));
    } else {
      Completer<Uint8List> completer = Completer<Uint8List>();
      List<int> contents = [];
      response.listen((c) => contents.addAll(c),
          onDone: () => completer.complete(Uint8List.fromList(contents)));
      return completer.future
          .then((uint8List) => ByteData.sublistView(uint8List))
          .then((bytes) => Try.success(bytes));
    }
  } on Exception catch (e, stacktrace) {
    Fimber.e("fetch ERROR", ex: e, stacktrace: stacktrace);
    return Try.failure(NetworkException(status: null, cause: e));
  }
}