Error while checking if URL is exists in Flutter

115

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;
  }
}
Share:
115
Superjay
Author by

Superjay

Student studying Flutter and UIUX designing.

Updated on January 02, 2023

Comments

  • Superjay
    Superjay 10 months

    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?

    • jamesdlin
      jamesdlin almost 2 years
      Have you tried catching the exception instead of leaving it unhandled?
    • gretal
      gretal almost 2 years
      REFER HERE: URL CHECK