How do I add a timeout if the http request fails?

I have an app that requests json data from Firebase. I have implemented a condition for unsuccessful codes however when there is a lack of connection, the request doesn't time out. Is there a way to add a timeout so that the AlertDialog will appear?

return http
    .post('https://flutter**********.com/products.json',
        body: json.encode(productData))
    .then((http.Response response) {
      if(response.statusCode != 200 && response.statusCode != 201) {
        _isLoading = false;
        notifyListeners();
        return false;
      }

false is returned when a different statusCode is received which in turn displays an AlertDialog allowing user to try again. It appears when code is deliberately broken but not when there is a lack of connectivity.

Thanks

1 answer

  • answered 2019-05-21 17:14 Richard Heap

    You can do it by using the underlying HttpClient. You can still use the http package utilities. You will have to catch the timeout exception. For example:

      HttpClient httpClient = HttpClient()
        ..connectionTimeout = Duration(seconds: 10);
      http.IOClient ioClient = http.IOClient(httpClient);
      ioClient.post(someUrl, body:etc); // this is equivalent of http.post, but with a timeout