如何修复Flutter中的"Exception caught by image resource service"异常
问题解决:Flutter中AssetImage加载Map中图片路径异常
问题原因
imagesIcon.values返回的是IterabletoString()后得到的是集合的字符串表示(类似(assets/images/test1.jpg, assets/images/test2.jpg, assets/images/test3.jpg)),这并不是合法的单个图片资源路径,因此AssetImage无法识别并加载资源,触发异常。而直接使用IconImages.test2时传入的是单个合法路径,所以能正常加载。
解决方案
根据生成三个对应不同图片的IconButton需求,提供两种可行方案:
方案1:遍历Map生成按钮(推荐)
通过遍历imagesIcon的entries,自动生成对应每个图片的按钮,避免重复代码:
Column( children: imagesIcon.entries.map((entry) { return Column( children: [ Container( color: Colors.lightBlueAccent, child: IconButton( icon: Image(image: AssetImage(entry.value)), onPressed: () {}, ), ), const SizedBox(height: 40), ], ); }).toList(), )
方案2:通过Map的Key获取单个路径
如果需要手动控制每个按钮对应的图片,直接通过Key取出Map中的单个路径:
Column( children: [ Container( color: Colors.lightBlueAccent, child: IconButton( // 通过Key=1获取对应路径,!用于空安全断言(确保Key存在) icon: Image(image: AssetImage(imagesIcon[1]!)), onPressed: () {}, ), ), const SizedBox(height: 40), Container( color: Colors.lightBlueAccent, child: IconButton( icon: Image(image: AssetImage(imagesIcon[2]!)), onPressed: () {}, ), ), const SizedBox(height: 40), Container( color: Colors.lightBlueAccent, child: IconButton( icon: Image(image: AssetImage(imagesIcon[3]!)), onPressed: () {}, ), ), ], ),
注意:空安全处理可以根据实际情况调整,比如用
imagesIcon[1] ?? IconImages.test1来提供默认路径,避免因Key不存在导致的空指针问题。
内容的提问来源于stack exchange,提问作者Verc
相关产品推荐
相关产品推荐

