Flutter Dart:无法加载SVG资源:无法加载资源iconPath。

5
我正在尝试使用flutter_svg软件包加载一些.svg图标。
class _MyHomePageState extends State<MyHomePage> {
  final String iconPath = "assets/icons/adept.svg";
  ...
}

我在pubspec.yaml文件中添加了包含icons/文件夹的assets/文件夹:

  assets:
    - assets/

当我尝试在我的页面中加载图标时:

      body: Center(
        child: Container(
          child: LimitedBox(
            child: SvgPicture.asset('iconPath', color: Colors.black, width: 100, height: 100,),
            maxHeight: 100,
            maxWidth: 100,
          )
        )
      ),

我得到了这个StackTrace:无法加载资源:assetName。

I/flutter (10154): ══╡ EXCEPTION CAUGHT BY SVG ╞═══════════════════════════════════════════════════════════════════════
I/flutter (10154): The following assertion was thrown resolving a single-frame picture stream:
I/flutter (10154): Unable to load asset: iconPath
I/flutter (10154): 
I/flutter (10154): When the exception was thrown, this was the stack:
I/flutter (10154): #0      PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:223:7)
...
I/flutter (10154): Picture provider: ExactAssetPicture(name: "iconPath", bundle: null, colorFilter: null)
I/flutter (10154): Picture key: AssetBundlePictureKey(bundle: PlatformAssetBundle#153a9(), name: "iconPath",
I/flutter (10154):   colorFilter: null)
I/flutter (10154): ════════════════════════════════════════════════════════════════════════════════════════════════════

请友善地解释我错过了什么?


1
尝试使用 SvgPicture.asset('assets/icons/adept.svg') - Andrej
@Andrej 感谢您指出我没有注意到的错误,正如您在下面的答案中所看到的,我必须在 pubspec.yaml 文件中包含 - assets/icons/,我原本以为只需要添加父文件夹,所有后续文件夹都会自动包含,但事实并非如此,很奇怪。 - user13848261
现在它能工作了吗? - Andrej
@Andrej 是的,谢谢。 - user13848261
2个回答

6

您是否像下面的代码一样进行了更改?

assets:
    - assets/
    - assets/icons/

      body: Center(
        child: Container(
          child: LimitedBox(
            child: SvgPicture.asset(iconPath, color: Colors.black, width: 100, height: 100,),
            maxHeight: 100,
            maxWidth: 100,
          )
        )
      ),

通过添加“- assets/icons/”解决了问题,但我认为如果我在“pubspec.yaml”中将一个文件夹包含为资源,则所有子文件夹都将自动包含,但正如本主题所示,这并不是情况。你能解释一下为什么吗? - user13848261
1
请查看官方网站评论:“https://flutter.dev/docs/development/ui/assets-and-images”。 - KuKu
只有位于目录直接位置的文件将被包含,除非在子目录中存在同名文件(请参阅Asset Variants)。若要添加位于子目录中的文件,请为每个目录创建一个条目。 - KuKu

3

只需执行3个步骤: 在终端中运行以下命令:flutter clean。

然后在Android Studio中打开“文件”菜单,选择“Invalidated caches and restarted”选项。

最后再次运行以下命令获取依赖项:flutter pub get


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接