Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while checking if URL is exists in Flutter

I want to check that the url exists or not.

Fuction:

Future _checkUrl(String url) async {
  http.Response _urlResponse =  await http.get(Uri.parse(url));
  if (_urlResponse.statusCode == 200) {
   return true;
  }
  else {
    return false;
  }
}

Call:

_checkUrl("https://stackoverf").then((value) => {
  print(value)
});

It works when I give https://fonts.google.com/?category=Sans+Serif (returns true) or https://stackoverflow.com/qu (returns false).

But when I try with https://stackoverf which is not valid, it gives me [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: SocketException: Failed host lookup: 'stackoverf' (OS Error: No address associated with hostname, errno = 7).

How to make _checkUrl returns false with this call?

like image 996
Superjay Avatar asked Apr 14 '26 22:04

Superjay


1 Answers

Would something like this work for what you want?

Future<bool> _checkUrl(String url) async {
  try {
    http.Response _urlResponse =  await http.get(Uri.parse(url));
    return _urlResponse.statusCode == 200;
    // return _urlResponse.statusCode < 400 // in case you want to accept 301 for example
  } on SocketException {
    return false;
  }
}
like image 191
h8moss Avatar answered Apr 16 '26 14:04

h8moss