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

Flutter使用Image.memory加载Base64图片遇FormatException错误求助

Flutter Base64图片加载报错:FormatException: Invalid character

我在Flutter中尝试通过Base64字符串加载图片,使用的代码如下:

class GeneratedImages extends StatelessWidget {
  const GeneratedImages({
    Key? key,
    required this.imageBytes,
  }) : super(key: key);
  final String imageBytes;

  @override
  Widget build(BuildContext context) {
    return Image.memory(
      const Base64Decoder().convert(imageBytes),
      errorBuilder: (_, object, stackTrace) {
        return const Center(
          child: Icon(Icons.image_not_supported),
        );
      },
    );
  }
}

运行后抛出错误:

FormatException: Invalid character (at character 77)

使用的Base64字符串片段:

/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEP
ERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4e
Hh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAEAAQA
FK5uYR9j05ISHI/eMTjPTGCPbtWJqHi3xJcyBhew27548oKMDPAG7k9cV1UsJWTu3YyqYml6n//Z

解决方法

  • 清理无效字符:Base64仅允许A-Z、a-z、0-9、+、/、=这些字符,你的字符串中存在换行符,先通过replaceAll(RegExp(r'\s'), '')移除所有空白字符(包括换行、空格)。
  • 使用base64Decode工具函数:替换Base64Decoder().convert()为dart:convert包中的base64Decode,它能处理更多格式兼容问题。
  • 验证Base64有效性:先通过在线工具转图片确认字符串是否完整、未被篡改。

修改后的代码示例:

import 'dart:convert';

class GeneratedImages extends StatelessWidget {
  const GeneratedImages({
    Key? key,
    required this.imageBytes,
  }) : super(key: key);
  final String imageBytes;

  @override
  Widget build(BuildContext context) {
    final cleanedBase64 = imageBytes.replaceAll(RegExp(r'\s'), '');
    return Image.memory(
      base64Decode(cleanedBase64),
      errorBuilder: (_, object, stackTrace) {
        return const Center(
          child: Icon(Icons.image_not_supported),
        );
      },
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 19:18:18