You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中使用GetConnect调用自定义API时Future/Await超时无响应返回Null的问题求助

Flutter GetConnect: 请求在响应超3秒时返回Null且await未等待完成

嘿,我知道你遇到的这个问题根源在哪——GetConnect默认的请求超时时间就是3秒!这就是为什么当API响应超过这个阈值时,请求会直接被中断,返回Null,而且await语句也不会继续等待响应完成。而你用其他方式调用API正常,是因为那些工具(比如Postman、curl)的默认超时时间通常比3秒长得多,能等到API返回结果。

下面是几个解决这个问题的具体方案:

1. 全局设置GetConnect的超时时间

如果你的大部分请求都需要更长的超时时间,可以在Provider的构造函数里全局配置:

class UsersProvider extends GetConnect {
  String url = Environment.API_URL + 'api';
  User user = User.fromJson(GetStorage().read('user') ?? {});

  UsersProvider() {
    // 设置全局超时为10秒,可根据实际需求调整时长
    httpClient.timeout = const Duration(seconds: 10);
  }

  Future<ResponseApi> prueba() async {
    Response response = await get('${url}/prueba', headers: {'Content-type': 'application/json'});
    if (response.body == null) {
      Get.snackbar('Error', 'No se pudo actualizar la información');
      return ResponseApi();
    }
    if (response.statusCode == 401) {
      Get.snackbar('Error', 'No estas autorizado');
      return ResponseApi();
    }
    ResponseApi responseApi = ResponseApi.fromJson(response.body);
    return responseApi;
  }
}

2. 为单个请求单独设置超时

如果只有个别请求需要更长的超时,也可以在具体的请求方法里指定:

Future<ResponseApi> prueba() async {
  Response response = await get(
    '${url}/prueba',
    headers: {'Content-type': 'application/json'},
    // 给这个请求单独设置10秒超时
    timeout: const Duration(seconds: 10),
  );
  // ... 原有处理逻辑
}

3. 添加超时异常捕获(推荐)

为了更清晰地排查问题,建议在请求里加上异常捕获,明确区分超时错误和其他类型的错误:

Future<ResponseApi> prueba() async {
  try {
    Response response = await get(
      '${url}/prueba',
      headers: {'Content-type': 'application/json'},
      timeout: const Duration(seconds: 10),
    );
    if (response.body == null) {
      Get.snackbar('Error', 'No se pudo actualizar la información');
      return ResponseApi();
    }
    if (response.statusCode == 401) {
      Get.snackbar('Error', 'No estas autorizado');
      return ResponseApi();
    }
    ResponseApi responseApi = ResponseApi.fromJson(response.body);
    return responseApi;
  } catch (e) {
    if (e is TimeoutException) {
      Get.snackbar('超时提示', '请求时间过长,请稍后重试');
      return ResponseApi();
    } else {
      Get.snackbar('Error', '请求失败:${e.toString()}');
      return ResponseApi();
    }
  }
}

另外提一句:你的测试API用超大循环模拟延迟,实际开发里尽量用异步延迟(比如PHP的sleep(5)),不过测试用的话就无所谓啦~

内容的提问来源于stack exchange,提问作者Alberto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 19:32:50