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

如何使用flutter_svg解析SVG字符串并捕获解析错误?

Flutter SVG 字符串有效性验证与错误处理方案

核心问题原因

SvgPicture.string 是同步构造方法,但内部解析逻辑是异步执行的,因此直接用 try/catch 无法捕获其内部抛出的错误,这就是你遇到捕获失效的根本原因。

可行解决方案

1. 提前用底层API验证SVG有效性

调用 flutter_svg 依赖的 svg 库解析方法,同步完成有效性校验:

import 'package:svg/svg.dart' as svg_parser;

Future<bool> isSvgValid(String svgString) async {
  try {
    await svg_parser.SvgParser().parseString(svgString);
    return true;
  } catch (_) {
    return false;
  }
}

使用时先验证再渲染:

FutureBuilder<bool>(
  future: isSvgValid(_shopLogoSvg),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      return snapshot.data == true
          ? SvgPicture.string(
              _shopLogoSvg,
              fit: BoxFit.contain,
              allowDrawingOutsideViewBox: false,
            )
          : const Center(child: Text("无效SVG")); // 替换为自定义错误占位UI
    } else {
      return const Center(child: CircularProgressIndicator());
    }
  },
);

2. 利用组件自身的错误回调

flutter_svg 1.0.0及以上版本支持 errorBuilder 参数,直接处理解析错误,无需额外验证:

SvgPicture.string(
  _shopLogoSvg,
  fit: BoxFit.contain,
  allowDrawingOutsideViewBox: false,
  placeholderBuilder: (context) => const Center(child: CircularProgressIndicator()),
  errorBuilder: (context, error, stackTrace) => const Center(child: Text("SVG加载失败")),
);

3. 修复FutureBuilder的溢出问题

如果坚持使用FutureBuilder,通过限制容器尺寸避免错误UI溢出:

FutureBuilder<String>(
  future: Future.value(_shopLogoSvg),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      return Container(
        constraints: const BoxConstraints(maxWidth: 200, maxHeight: 200),
        child: SvgPicture.string(
          snapshot.data!,
          fit: BoxFit.contain,
          allowDrawingOutsideViewBox: false,
          errorBuilder: (_, __, ___) => const Center(child: Text("无效SVG")),
        ),
      );
    } else {
      return const Center(child: CircularProgressIndicator());
    }
  },
);

关键提示

  • 确保使用最新版 flutter_svg,旧版本可能缺失 errorBuilder 等核心API。
  • 不可信SVG除格式错误外可能存在安全风险,验证时建议限制外部资源引用等危险内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 16:02:34