Flutter Image.asset加载资源图报AbortError异常解决方案
问题背景
在Flutter 3.0.3版本开发过程中,通过Positioned组件实现图片上叠加文字的效果,已确认图片路径正确,且已在pubspec.yaml文件中添加对应资源配置,但图片展示时抛出异常。
完整报错信息
══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞════════════════════════════════════════════════════ The following DomException object was thrown resolving an image frame: AbortError: Aborted by failure. When the exception was thrown, this was the stack Image provider: AssetImage(bundle: null, name: "assets/images/contact_us_banner.png") Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#b62cd(), name: "assets/images/contact_us_banner.png", scale: 1)
复现代码
import 'package:flutter/material.dart'; import '../../../../constants/images.dart'; class ContactUsContainer extends StatelessWidget { @override Widget build(BuildContext context) { double width = MediaQuery.of(context).size.width; return Padding( padding: const EdgeInsets.symmetric(vertical: 60, horizontal: 20), child: Container( color: const Color(0xff9ABFC7), height: 200, width: width * 0.80, child: Stack(children: [ Image.asset(contactUsBanner, fit: BoxFit.contain), const Positioned( top: 20, left: 20, child: Text("Let's Build Your Website!", style: TextStyle( color: Colors.white, fontSize: 40, wordSpacing: 2, letterSpacing: 2, fontWeight: FontWeight.w900))) ]), ), ); } }
异常产生原因
- 该报错是Flutter 3.0.3版本Web端CanvasKit渲染器的已知兼容问题:当
Image.asset直接作为Stack的子组件、父容器同时设置固定宽高但未给图片明确布局约束时,渲染时序冲突会导致图片解码服务中断加载,抛出DomException类型的AbortError,该问题和资源路径、pubspec.yaml配置正确性无关。 - 图片文件本身编码不兼容Web端解码规则也会触发该错误,比如图片使用CMYK色彩通道、携带异常元数据标记、Alpha通道损坏时,CanvasKit渲染器无法正常解码图片就会中断加载。
- 资源更新后仅使用热重载、未执行全量重启,会导致新添加的资源没有被正确打包到Asset bundle中,触发加载中断。
解决方法
- 给
Stack内的图片组件明确布局约束,将直接挂载的Image.asset包裹在Positioned.fill中,同时给Stack设置裁剪属性避免布局溢出,参考修改代码:
Stack( clipBehavior: Clip.hardEdge, children: [ Positioned.fill( child: Image.asset(contactUsBanner, fit: BoxFit.cover), ), const Positioned( top: 20, left: 20, child: Text("Let's Build Your Website!", style: TextStyle( color: Colors.white, fontSize: 40, wordSpacing: 2, letterSpacing: 2, fontWeight: FontWeight.w900))) ], )
- 临时规避CanvasKit渲染器bug:Web端运行或打包时指定使用Html渲染器,调试启动命令为
flutter run -d chrome --web-renderer html,生产打包命令为flutter build web --web-renderer html。 - 校验图片编码格式:将目标图片转换为sRGB色彩通道的标准PNG/JPG格式,清除多余元数据后替换原资源文件,执行
flutter clean清除缓存后全量重启应用,不要使用热重载加载更新后的资源。 - 长期修复方案:升级Flutter到3.3及以上稳定版本,官方已在该版本分支修复Web端Stack下AssetImage加载触发AbortError的渲染时序问题。
内容的提问来源于stack exchange,提问作者H_R_S
相关产品推荐
相关产品推荐

