Search code examples
flutterdartdio

dio BaseOptions connectTimeout receiveTimeout doesn't work


My connectTimeout and receiveTimeouts don't work. Here is my code:

BaseOptions options = new BaseOptions(
    baseUrl: 
        'http://localhost:5000/api',
    connectTimeout: 5000,
    receiveTimeout: 3000,
    responseType: ResponseType.plain);

Dio myDio = new Dio(options);

// api file
      final response = await myDio.get('/test');

// on the backend in Node.js, i delay my response with:
        setTimeout(function () { res.status(201).json(result) }, 50000)

However, this does not work. What is interesting however, is that if I do this it works:

myDio.options.connectTimeout = 5000; 
myDio.options.receiveTimeout = 3000;

final response = await myDio.get('/test');

I don't really want to do this, since I have many api calls and I want my myDio instance to take care of all the timeouts. Any idea how to get around this, or what is going on?

Thanks


Solution

  • You could create a utility class that gives you a "pre-configured" Dio object, something along these lines:

    class WebUtil {
    
        static Dio createDio() {
        var dio = Dio(
            BaseOptions(
                baseUrl: "${AppSettings.webServiceUrl}/api/",
                headers: {
                  "Accept": "application/json",
                }
            )
        );
        dio.options.connectTimeout = 5000;
        dio.options.receiveTimeout = 3000;
        return dio;
      }
    }
    
      // Nothing to do with your question, just a simple helper method to parse Dio exceptions:
      static String getUserExceptionMessage(DioError dioError) {
        return '${dioError.response.statusCode}: ${dioError.response.statusMessage}.\nURL: ${dioError.request.path}';
      }
    }
    

    To use:

    Response response = await WebUtil.createDio().get("some-call");