setFromURL method

Future<bool> setFromURL(
  1. BuildContext context, {
  2. required String url,
  3. Map<String, String>? headers,
  4. int? maxSize,
  5. dynamic onAdd()?,
})

Implementation

Future<bool> setFromURL(final BuildContext context, {
  required final String url,
  final Map<String, String>? headers,
  final int     ? maxSize,
  final Function()? onAdd
}) async {

  // Validate URL format
  if (!_urlPattern.hasMatch(url)) {
    error = true;
    fromLoading = false;
    throw Exception("The URL is not valid");
  }

  Request request = Request("GET", Uri.parse(url))..followRedirects = false;

  // Add headers if provided
  if (headers != null) request.headers.addAll(headers);

  return await request.send().then((value) async {
    if (value.statusCode == 200) {
      try {
        final image_name_extendion = url.split('/').last.split('.');

        await value.stream.toBytes().then((bytes) async => await setFromBytes(
          name      : _className,
          bytes     : bytes,
          extension : image_name_extendion.last,
          maxSize   : maxSize,
          onAdd     : onAdd
        ))
        .onError((error, stackTrace) {
          _reset(error: true);
          return false;
        });

        return true;
      } catch (e) {
        _reset(error: true);
        return false;
      }
    } else {
      _reset(error: true);
      return false;
    }
  }).onError((error, stackTrace){
      _reset(error: true);
      return false;
  });
}