检查 Flutter 中是否存在 URL 时出错

Error while checking if URL is exists in Flutter

我想检查 url 是否存在。

函数:

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

通话:

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

当我给出 https://fonts.google.com/?category=Sans+Serif(returns true)或 https://whosebug.com/qu(returns false)时有效。

但是当我尝试使用无效的 https://stackoverf 时,它给了我 [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).

如何通过此调用使 _checkUrl returns 为假?

这样的东西能满足您的需求吗?

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;
  }
}