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

Flutter Dio连接超时问题:真机API调用偶现超时,模拟器正常

解决Flutter真机Dio调用API随机出现ConnectTimeout问题
  • 管好请求资源,避免连接池耗尽
    真机频繁切换页面时,很可能是未及时取消无用请求导致连接池被占满。发起请求时带上CancelToken,页面销毁时主动取消:

    CancelToken _cancelToken = CancelToken();
    
    // 发起请求时传入cancelToken
    dio.post('/api/xxx', cancelToken: _cancelToken);
    
    // 页面销毁时执行取消操作
    @override
    void dispose() {
      _cancelToken.cancel('页面已销毁');
      super.dispose();
    }
    

    同时可以调大Dio单主机允许的连接数,缓解连接不足的问题:

    Dio dio = Dio(BaseOptions(
      connectTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 10),
    ))..httpClientAdapter = HttpClientAdapter()..createHttpClient = () {
      final client = HttpClient();
      client.maxConnectionsPerHost = 10; // 增大单域名连接数上限
      return client;
    };
    
  • 关闭真机上的代理/VPN
    部分真机开启的系统代理、VPN或第三方网络工具,会干扰API请求,频繁调用时容易出现异常。直接使用运营商网络测试,排除这类外部干扰。

  • 对比成功与失败请求的参数和请求头
    别只盯着超时错误,切换页面时的请求可能存在参数或请求头异常(比如token失效、参数格式错误),导致服务器未响应进而触发超时。请求前打印完整的URL、headers、data,对比成功和失败请求的差异,定位问题。

  • iOS真机检查ATS配置
    即使SSL正常,iOS的ATS(App Transport Security)可能存在隐性限制。可以先在Info.plist中添加宽松配置测试(上线前需恢复严格配置):

    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSAllowsArbitraryLoads</key>
      <true/>
    </dict>
    

    或者针对你的API域名单独配置:

    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSExceptionDomains</key>
      <dict>
        <key>你的API域名.com</key>
        <dict>
          <key>NSIncludesSubdomains</key>
          <true/>
          <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
          <true/>
          <key>NSTemporaryExceptionMinimumTLSVersion</key>
          <string>TLSv1.2</string>
        </dict>
      </dict>
    </dict>
    
  • 升级Dio到最新稳定版
    旧版本Dio可能存在真机网络适配的bug,直接在pubspec.yaml中更新版本:

    dio: ^5.4.0+1 # 替换为当前最新稳定版
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 20:15:38