dio BaseOptions connectTimeout receiveTimeout不起作用

时间:2019-10-22 19:04:08

标签: flutter dart dio

我的connectTimeout和receiveTimeouts不起作用。这是我的代码:

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)

但是,这不起作用。但是有趣的是,如果我这样做,它会起作用:

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

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

我真的不想要这样做,因为我有很多api调用,并且我希望myDio实例能够处理所有超时。知道如何解决这个问题,或发生了什么事?

谢谢

1 个答案:

答案 0 :(得分:1)

您可以创建一个实用程序类,为您提供一个“预配置”的Dio对象,类似于以下几行:

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

要使用:

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