You need to enable JavaScript to run this app. Flutter中Future内部能否对失败的HTTP请求执行重试操作?
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中Future内部能否对失败的HTTP请求执行重试操作?

方案1:函数内置重试计数(推荐,无需修改上层调用)

直接给现有方法增加可选的重试计数参数,在请求失败时递归调用自身,所有分支都有明确返回值,不会出现Future非空报错的问题:

Future<Result> getJSONfromTheSite(String call, {int retryCount = 0}) async {
  debugPrint('Network Attempt by getJSONfromTheSite: 第${retryCount + 1}次尝试');
  try {
    final response = await http.get(Uri.parse('http://www.thesite.com/'));

    if (response.statusCode == 200) {
      return Result<AppData>.success(AppData.fromRawJson(response.body));
    } else {
      // 未达到最大重试次数(共3次)则继续重试
      if (retryCount < 2) {
        return await getJSONfromTheSite(call, retryCount: retryCount + 1);
      }
      // 重试耗尽返回错误
      return Result.error(title:"Error",msg:"Status code not 200", errorcode:1);
    }
  } catch (error) {
    if (retryCount < 2) {
      // 可选:增加重试间隔,避免短时间频繁请求被限流
      await Future.delayed(const Duration(milliseconds: 1000));
      return await getJSONfromTheSite(call, retryCount: retryCount + 1);
    }
    return Result.error(title:"No connection",msg:"Status code not 200", errorcode:0);
  }
}

调用方式和原有逻辑完全一致,不需要修改上层代码。

方案2:封装通用重试工具(适合多请求需要重试的场景)

如果项目中有多个接口都需要重试逻辑,可以封装通用的重试工具函数,复用性更高:

// 通用重试工具,支持自定义重试次数、退避延迟
Future<T> runWithRetry<T>(
  Future<T> Function() request, {
  int maxRetries = 3,
  Duration delay = const Duration(milliseconds: 500),
}) async {
  int currentAttempt = 0;
  while (true) {
    try {
      currentAttempt++;
      return await request();
    } catch (e) {
      if (currentAttempt >= maxRetries) rethrow;
      // 可选:指数退避,重试间隔随次数增加
      await Future.delayed(delay * currentAttempt);
    }
  }
}

改造原请求方法,将异常抛出触发重试逻辑:

Future<Result> getJSONfromTheSite(String call) async {
  return runWithRetry(() async {
    debugPrint('Network Attempt by getJSONfromTheSite');
    final response = await http.get(Uri.parse('http://www.thesite.com/'));
    if (response.statusCode == 200) {
      return Result<AppData>.success(AppData.fromRawJson(response.body));
    }
    // 状态码异常主动抛出,触发重试
    throw Exception("status code error");
  }).catchError((error) {
    // 重试全部失败后统一返回错误
    if (error.toString().contains("status code error")) {
      return Result.error(title:"Error",msg:"Status code not 200", errorcode:1);
    }
    return Result.error(title:"No connection",msg:"Status code not 200", errorcode:0);
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 18:21:02