flutter 无法加载和渲染 svg 图像

flutter cannot load and render svg images

我正在尝试加载和显示 svg 格式的图像,但我每次都会收到此错误

unhandled element pattern; Picture key: AssetBundlePictureKey(bundle: PlatformAssetBundle#5abbc(), name: "assets/svg/Ellipse.svg", colorFilter: null)
══╡ EXCEPTION CAUGHT BY SVG ╞═══════════════════════════════════════════════════════════════════════
The following assertion was thrown while parsing AssetBundlePictureKey(bundle:
PlatformAssetBundle#5abbc(), name: "assets/svg/Ellipse.svg", colorFilter: null) in
_getDefinitionPaint:
Failed to find definition for url(#pattern0)
This library only supports <defs> and xlink:href references that are defined ahead of their
references.
This error can be caused when the desired definition is defined after the element referring to it
(e.g. at the end of the file), or defined in another file.
This error is treated as non-fatal, but your SVG file will likely not render as intended
════════════════════════════════════════════════════════════════════════════════════════════════════

这就是我尝试显示它的方式

Padding(
  padding: const EdgeInsets.only(top: 24),
  child: SvgPicture.asset(
   'assets/svg/Ellipse.svg',
   width: 100,
   height: 100,
 ),
),

如何修复错误

尝试使用 flutter_svg 库。这将在您的 flutter 应用程序中呈现 SVG。

Link: https://pub.dev/packages/flutter_svg

基本用法:

final String assetName = 'assets/image.svg';
final Widget svg = SvgPicture.asset(
  assetName,
  semanticsLabel: 'Acme Logo'
);

Flutter 本身不支持渲染 SVG。但是有一些解决方法。

解决方案 1:有一个名为 flutter_svg 的包,它提供了一种将 SVG 添加到 flutter 项目的可靠方法。

解决方案 2:使用免费的在线转换器将您的 SVG 文件转换为 PNG(示例:https://svgtopng.com/)。