【问题标题】:How to catch an Error for timeout on http.client Flutter如何在 http.client Flutter 上捕获超时错误
【发布时间】:2023-02-13 19:48:15
【问题描述】:

我有一个使用 http.client 结构调用 POST API 的 Future。

目前,上述 API 存在问题,我的调用在收到完整标头之前超时,给我一个未处理的异常。

返回此异常并显示返回问题的快餐栏的最佳方法是什么?

  Future<dynamic> get() async {
try {
  var response = await client.post(
    Uri.parse(Url),
    headers: headers,
    body: body,
  );

}

【问题讨论】:

  • 你在使用FutureBuilder吗?如果是这样,检查snapshot.hasError属性

标签: flutter dart


【解决方案1】:

这是捕获超时错误的简单 http 调用

返回错误并在你处理 api 调用的地方捕获它

import 'package:http/http.dart';

Future<dynamic> get() async {
  try {
    var response = await post(
      Uri.parse(Url),
      headers: headers,
      body: body,
    ).timeout(Duration(seconds: 2), onTimeout: (){
      /// here is the response if api call time out
      /// you can show snackBar here or where you handle api call
      return Response('Time out!', 500);
    });
  }catch(e){
    print(e);
  }
}

您可以在超时方法中更改持续时间

【讨论】:

    猜你喜欢
    • 2021-04-15
    • 2016-01-21
    • 1970-01-01
    • 2018-01-08
    • 2012-07-21
    • 2020-05-23
    • 2021-02-05
    • 1970-01-01
    • 2013-08-18
    相关资源
    最近更新 更多