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

Flutter应用图片加载失败:HttpException连接中断问题求助

Flutter图片加载异常(Connection closed while receiving data)解决方法

1. 移除压缩编码请求头

当前ApiClient的请求头中包含Accept-Encoding: gzip, deflate, br,部分场景下Flutter图片解码逻辑对压缩响应的处理存在兼容性问题,容易触发连接中断。建议暂时移除该头部:

_mainHeaders = {
  "Content-type": "application/json; charset=UTF-8",
  "Authorization": "Bearer $token",
  // 'Accept-Encoding': 'gzip, deflate, br', // 注释或删除此行
};

2. 统一模拟器访问地址

确保所有图片请求的BaseUrl统一使用10.0.2.2:8000(Android模拟器对应本地127.0.0.1的映射地址),避免混合使用127.0.0.1和10.0.2.2导致部分请求失败。

3. 延长网络超时时间

当前30秒的超时设置可能不足以加载较大的图片,可适当延长超时时长:

timeout = Duration(seconds: 60);

4. 验证服务器图片返回完整性

用Postman或浏览器直接请求图片的完整URL(如http://10.0.2.2:8000/path/to/image.jpg),确认图片能完整下载,同时检查服务器返回的Content-Type是否正确(如image/jpeg、image/png),排除服务器端传输中断问题。

5. 使用Flutter原生Image.network加载图片

若你是通过自定义ApiClient获取图片数据后再显示,可尝试直接用Flutter原生的Image.network组件,并携带必要的请求头,利用原生稳定的图片加载机制:

Image.network(
  'http://10.0.2.2:8000/path/to/your/image.jpg',
  headers: {
    "Authorization": "Bearer ${AppConstants.TOKEN}",
  },
  errorBuilder: (context, error, stackTrace) {
    print(error); // 打印具体错误便于排查
    return Icon(Icons.broken_image); // 显示错误占位图标
  },
)

6. 完善网络安全配置

检查network_security_config.xml,确保允许10.0.2.2的明文流量访问:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 14:51:09