0

我的 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实例处理所有超时。知道如何解决这个问题,或者发生了什么?

谢谢

4

1 回答 1

4

您可以创建一个实用程序类,为您提供“预配置”的 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");
于 2019-10-24T16:24:59.637 回答