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

Flutter中如何从主项目向组件包传递资源图片路径

问题原因

组件包中直接使用AssetImage(src)时,默认会从组件包自身的资源目录查找图片,但你需要加载的是主项目的资源——两者的AssetBundle是相互独立的,因此无法匹配到目标资源。

修复方案

修改组件包的ContainerDeco代码,使用当前上下文的DefaultAssetBundle来加载主项目的资源:

class ContainerDeco extends StatelessWidget {
  const ContainerDeco(this.src, {Key? key}) : super(key: key);
  final String src;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          // 指定使用主项目的AssetBundle加载资源
          image: AssetImage(src, bundle: DefaultAssetBundle.of(context)),
        ),
      ),
    );
  }
}
额外检查项
  • 主项目pubspec.yaml的资源配置已经覆盖了目标图片路径,无需调整。
  • 调用时传入的路径assets/images/lockup_flutter_horizontal.png完全匹配资源位置,路径正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 01:57:44