getURLData function

Future<Uint8List> getURLData(
  1. String url, {
  2. String? user,
  3. String? password,
  4. bool withCredentials = true,
})

Makes a HTTP request and returns url content as Uint8List.

Implementation

Future<Uint8List> getURLData(String url,
    {String? user, String? password, bool withCredentials = true}) {
  var httpRequest = HttpRequest();

  httpRequest.withCredentials = withCredentials;

  httpRequest.responseType = 'arraybuffer';

  var completer = Completer<Uint8List>();

  httpRequest.onLoad.listen((event) {
    var status = httpRequest.status;
    if (status == 200) {
      var response = httpRequest.response;
      var data = Uint8List.view(response);
      completer.complete(data);
    } else {
      completer.completeError('Invalid response status: $status');
    }
  }, onError: (error) {
    completer.completeError(error);
  });

  httpRequest.onError.listen((event) {
    completer.completeError(event);
  });

  httpRequest.open('GET', url, async: true, user: user, password: password);

  httpRequest.send();

  return completer.future;
}