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

如何在flutter_svg的SvgPicture.network()中处理网络错误并重试加载

Flutter SVG网络加载错误重试实现方案

实现思路

借助SvgPicture.network的errorBuilder回调结合状态管理,实现手动/自动重试加载逻辑,同时限制最大重试次数避免无限循环。

完整代码实现

自定义带重试逻辑的SVG组件

class RetrySvg extends StatefulWidget {
  final String imageUrl;
  final double width;
  final double height;
  final BoxFit fit;
  final int maxRetry; // 可配置最大重试次数

  const RetrySvg({
    super.key,
    required this.imageUrl,
    required this.width,
    required this.height,
    required this.fit,
    this.maxRetry = 3,
  });

  @override
  State<RetrySvg> createState() => _RetrySvgState();
}

class _RetrySvgState extends State<RetrySvg> {
  int _currentRetry = 0;

  void _triggerRetry() {
    if (_currentRetry < widget.maxRetry) {
      setState(() => _currentRetry++);
    }
  }

  @override
  Widget build(BuildContext context) {
    return SvgPicture.network(
      widget.imageUrl,
      width: widget.width,
      height: widget.height,
      fit: widget.fit,
      // 加载中占位
      placeholderBuilder: (_) => const CircularProgressIndicator(strokeWidth: 2),
      errorBuilder: (context, error, stackTrace) {
        // 达到最大重试次数,显示错误占位
        if (_currentRetry >= widget.maxRetry) {
          return const Icon(Icons.broken_image, size: 24, color: Colors.grey);
        }
        // 点击图标触发重试
        return GestureDetector(
          onTap: _triggerRetry,
          child: const Icon(Icons.refresh, size: 24, color: Colors.blue),
        );
      },
    );
  }
}

组件使用示例

RetrySvg(
  imageUrl: "https://example.com/your-icon.svg",
  width: 24.0,
  height: 24.0,
  fit: BoxFit.fitHeight,
  maxRetry: 5, // 可选:自定义最大重试次数
)

扩展优化

  • 自动重试:如果需要无需手动点击自动重试,可在errorBuilder中添加延迟重试逻辑:
    errorBuilder: (context, error, stackTrace) {
      if (_currentRetry < widget.maxRetry) {
        Future.delayed(const Duration(seconds: 2), _triggerRetry);
        return const CircularProgressIndicator(strokeWidth: 2);
      }
      return const Icon(Icons.broken_image, size: 24);
    }
    
  • 自定义占位UI:可根据需求替换placeholderBuilder和错误状态下的Widget,比如使用文字提示或自定义错误图标。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 07:07:20