Flutter中无法加载Asset图片:问题排查与解决求助
Flutter 资源加载错误:Unable to load asset: "assets/heart.png"
问题详情
我编写的Flutter代码如下:
@override Widget build(BuildContext context) { return Scaffold( backgroundColor: const Color.fromARGB(255, 158, 202, 239), body: Center( child: Container( decoration: const BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(5))), height: 250, width: 180, child: Center( child: Container( child: const Image( image: AssetImage('assets/heart.png'), ), ), ), )), ); } }
运行后抛出错误:
The following assertion was thrown resolving an image codec:
Unable to load asset: "assets/heart.png".Exception: Asset not found
我的pubspec.yaml配置:
# The following section is specific to Flutter packages. flutter: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true # To add assets to your application, add an assets section, like this: assets: - assets/joker.jpeg - assets/heart.png
解决方案
- 核对文件实际位置:确认项目根目录下存在
assets文件夹,且heart.png确实在该文件夹中,注意文件名大小写(Flutter对大小写敏感,Heart.png和heart.png会被视为不同文件)。 - 检查pubspec.yaml缩进:YAML配置对缩进要求严格,确保
assets列表的每一项(如- assets/heart.png)前面的短横线与assets:保持正确的层级缩进(通常为2个空格)。 - 清理缓存并重启服务:执行
flutter clean清除旧的资源缓存,然后重新运行flutter run加载最新的资源配置。 - 确认路径一致性:代码中
AssetImage('assets/heart.png')的路径需与pubspec.yaml中配置的完全一致,避免多写或漏写斜杠。
内容的提问来源于stack exchange,提问作者MattPrash
相关产品推荐
相关产品推荐

