【问题标题】:Dart Dio Package `DioError` `request` Object not definedDart Dio 包 `DioError` `request` 对象未定义
【发布时间】:2021-09-07 11:10:00
【问题描述】:

https://pub.dev/packages/dio#handling-errors 的 Dart Dio 包文档中描述了如何处理错误:

try {
  //404
  await dio.get('https://wendux.github.io/xsddddd');
} on DioError catch (e) {
  // The request was made and the server responded with a status code
  // that falls out of the range of 2xx and is also not 304.
  if (e.response) {
    print(e.response.data)
    print(e.response.headers)
    print(e.response.request)
  } else {
    // Something happened in setting up or sending the request that triggered an Error
    print(e.request)
    print(e.message)
  }
}

代码很有意义,并为我提供了了解我的请求发生了什么所需的选项,但 Android Studio 中的 Dart 分析工具(我正在开发一个 Flutter 应用程序)对此反应剧烈。

按照 Android Studio 的建议,我可以通过在代码中添加空检查来解决许多分析器的投诉:

try {
    var response = await dio.get(url, options: options);
    print('Response: $response');
    return response.data;
} on DioError catch (e) {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx and is also not 304.
    if (e.response != null) {
      print(e.response!.data);
      print(e.response!.headers);
      print(e.response!.request);  <-- line 64
    } else {
      // Something happened in setting up or sending the request that triggered an Error
      print(e.request);  <-- line 67
      print(e.message);
    }
}

但分析器仍然抱怨request 对象:

error: The getter 'request' isn't defined for the type 'Response<dynamic>'. (undefined_getter at [particle_cloud] lib\src\particle.dart:64)
error: The getter 'request' isn't defined for the type 'DioError'. (undefined_getter at [particle_cloud] lib\src\particle.dart:67)

我假设 DioError 应该定义了适当的请求对象,我该如何修复此代码以使其运行?

【问题讨论】:

    标签: dart dio


    【解决方案1】:

    API 更改时,他们的自述文件没有更新。新 API 中的 request 等价于 requestOptions。这可以通过查看API reference 轻松找到。

    print(e.requestOptions);
    

    【讨论】:

    • 谢谢。那行得通。我向 Dio 团队提交了 PR 来修复文档。
    猜你喜欢
    • 2021-03-01
    • 1970-01-01
    • 2021-12-04
    • 2016-10-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2015-03-05
    相关资源
    最近更新 更多