skip to Main Content

When doing a HTTP request in Flutter I do not get any Exception like SocketException when WiFi is on but there is actually no internet, rather it waits long time until I get the defined TimeoutException. Also this issue appears when there is network connection in the beginning but suddenly the connection drops.

How do I make it that it directly gives an exception whenever network issues occur?

This my current code:

try {
  await http
      .get(url, headers: headers)
      .timeout(const Duration(seconds: 20));
} on SocketException catch (e, st) {
  debugPrint('SocketException. Seems to be no internet available');
  debugPrint(e.toString());
  debugPrint('OS Errorcode: ${e.osError?.errorCode.toString()}');
} catch (e, st) {
  debugPrint('Unknown error happen in `tryAndHandle`:');
}

2

Answers


  1. Actually there is no way to do this without pinging different urls to make sure there is internet.

    Or use flutter_offline to detect changes and response accordingly.

    enter image description here

    Login or Signup to reply.
  2. SocketException somehow does not detect no internet connect what I am using is something like normal Exception it does get triggered only when internet is not available or when request does not proceed. All other Exceptions like timeout etc.. are return as form of http.Response object, you can handle them through that.

    @override
    Future<http.Response?> putHttp(
      {required String endPoint,
      Duration timeOut = const Duration(seconds: timeOutDuration),
      Map<String, String>? headers,
      Map<String, dynamic>? requestBody}) async {
    try {
      // call http request
      http.Response response = await http
          .put(
            Uri.parse(endPoint),
            body: requestBody,
            headers: headers,
          )
          .timeout(timeOut);
    
      return response;
    } on Exception catch (_) {
      return null;
    }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search