setFromURL method

Future<bool> setFromURL(
  1. BuildContext context, {
  2. required String url,
  3. Map<String, String>? headers,
})

Implementation

Future<bool>setFromURL(BuildContext context, {required String url, Map<String, String>? headers}) async {
  List<String> list = url.split("://");
  if (list.length <= 1) {
    error = true;
    fromLoading = false;
    throw Exception("The URL is not valid");
  }

  String type = list.first.toLowerCase();
  list = list.last.split("/");
  String domain = list.first;
  list.remove(domain);
  String path = list.join("/");

  List<String> _n = list.last.split(".");
  if (_n.length <= 1) throw Exception("URL dont have extension");
  if (_n.length != 2) throw Exception("URL dont have a valid image");

  Request request = Request(
    "GET",
    type.toLowerCase() == 'https'
    ? Uri.https(domain, path, headers)
    : Uri.http(domain, path, headers)
  );

  request.followRedirects = false;
  return await request.send().then((value) async{
    if(value.statusCode == 200){
      try{
        await value.stream.toBytes().then((bytes) async => await setFromBytes(
          name      : DateTime.now().millisecondsSinceEpoch.toString() + Random().nextInt(10000).toString() + '-' + _n.first,
          bytes     : bytes,
          extension : _n.last
        ));

        return true;
      } catch (e) {
        _reset(error: true);
        return false;
      }
    } else {
      _reset(error: true);
      return false;
    }
  });
}