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

使用flutter_svg的SvgPicture.network()出现XmlParserException错误求助

Flutter SVG加载报错解决方案

针对你使用flutter_svg的SvgPicture.network()加载网络SVG时出现的unhandled element <style/>和XmlParserException错误,提供以下几种解决方式:

1. 允许flutter_svg解析未知元素

通过自定义SvgParser,让库忽略不支持的元素和属性,避免报错:

SvgPicture.network(
  "https://myAdrees.com/${e.logoGrey}",
  width: 30,
  height: 30,
  color: Colors.grey,
  parser: const SvgParser(
    allowUnknownElements: true,
    allowUnknownAttributes: true,
  ),
)

2. 预处理SVG内容修复格式问题

如果报错是因为SVG本身XML语法错误(比如未闭合标签),可以先获取SVG文本并修复后再加载:

// 先添加http依赖到pubspec.yaml:dependencies: http: ^1.1.0
FutureBuilder<String>(
  future: http.get(Uri.parse("https://myAdrees.com/${e.logoGrey}"))
      .then((res) => res.body)
      .then((svgTxt) {
        // 移除<style>标签或修复XML语法,这里示例移除<style>
        return svgTxt.replaceAll(RegExp(r'<style[^>]*>.*?</style>', dotAll: true), '');
      }),
  builder: (ctx, snapshot) {
    if (snapshot.hasData) {
      return SvgPicture.string(
        snapshot.data!,
        width: 30,
        height: 30,
        color: Colors.grey,
      );
    }
    return snapshot.hasError 
        ? const Icon(Icons.error_outline) 
        : const CircularProgressIndicator(size: 20);
  },
)

3. 升级flutter_svg到最新版本

旧版本库对SVG特性支持有限,执行命令升级:

flutter pub upgrade flutter_svg

4. 修复源SVG文件

如果有权限修改服务器上的SVG文件,直接修正以下问题:

  • 确保<style>标签正确闭合,移除无效CSS代码
  • 修复XML语法错误(比如报错提示的77:21位置缺少>)
  • 使用flutter_svg支持的SVG特性(避免使用复杂CSS或不兼容元素)

内容的提问来源于stack exchange,提问作者salih balsever

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 09:30:11