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

Flutter中如何解析API返回的SVG字符串并在ListView中作为图标展示

Flutter 接口返回SVG字符串列表展示方案

1. 引入依赖

在项目的pubspec.yaml文件中添加渲染SVG的三方依赖:

dependencies:
  flutter:
    sdk: flutter
  # 版本可根据你的Flutter版本选择适配的稳定版
  flutter_svg: ^2.0.9

添加完成后执行flutter pub get完成依赖安装。

2. 核心实现

flutter_svg提供了直接解析SVG字符串的构造方法SvgPicture.string,可以直接传入接口返回的SVG格式字符串完成渲染,无需先转存为本地文件。

ListView中使用示例

假设你已经从接口获取到了SVG字符串列表svgStringList,完整的列表渲染代码如下:

import 'package:flutter_svg/flutter_svg.dart';

class SvgIconList extends StatelessWidget {
  // 接口返回的SVG字符串列表
  final List<String> svgStringList;

  const SvgIconList({super.key, required this.svgStringList});

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: svgStringList.length,
      itemBuilder: (context, index) {
        final svgStr = svgStringList[index];
        return ListTile(
          // 左侧展示SVG图标
          leading: SvgPicture.string(
            svgStr,
            width: 24,
            height: 24,
            fit: BoxFit.contain,
            // 可选:渲染失败时展示的占位图标
            errorBuilder: (context, error, stackTrace) {
              return const Icon(Icons.broken_image, size: 24);
            },
          ),
          title: Text('图标 ${index+1}'),
        );
      },
    );
  }
}

你提供的示例SVG字符串符合标准格式,可直接用上述方法正常渲染。

3. 注意事项

  • 需确保接口返回的SVG字符串无语法错误、无自定义非标准标签,否则会出现渲染异常
  • 长列表场景下可配合内存缓存策略存储解析后的SVG数据,减少重复解析的性能开销
  • 若需要修改SVG的填充颜色,可配合colorFilter属性实现颜色替换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:06:03