Base64:invalid 长度必须是四的倍数:flutter 错误

Base64:invalid length must be multiple of four : Error in flutter

我得到了图片Base64编码的图片数据,但是我得到的其中一张图片没有上传,报错

invalid length must be multiple of four.

另外,我的其他图片出现了片刻,片刻消失了。他们来来去去。这个问题有解决方案吗?

     Widget image(String thumbnail) {
        final _byteImage = Base64Decoder().convert(thumbnail);
        Widget image = Image.memory(_byteImage);
        return image;
      }

 child: Column(
                    children: [
                      image(item.thumbnail),
                      Text(
                        item.name,
                        style: TextStyle(fontSize: 14, fontWeight: FontWeight.normal,fontFamily: 'Poppins'),
                        maxLines: 2,
                      ),
                    ],
                  ),

您需要用一个或两个“=”填充 Base64 字符串以达到 4 的倍数的长度。

如果能不休息地除以4就好了。如果长度模 4 的余数是 3,则添加 1 '=',如果余数是 '2,则将 2 '=' 添加到字符串。

在 dart 中,您使用 "".length 获取字符串的长度,然后使用模运算符 %:

计算除以 4 的余数

由于实际问题原来是空字符串,因此以下代码也 并显示占位符图像而不是错误消息。

Widget image(String thumbnail) {
        String placeholder = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
        if (thumbnail?.isEmpty ?? true)
            thumbnail = placeholder;
        else {
            if (thumbnail.length % 4 > 0) { 
                thumbnail += '=' * (4 - thumbnail .length % 4) // as suggested by Albert221
            }
        }
        final _byteImage = Base64Decoder().convert(thumbnail);
        Widget image = Image.memory(_byteImage);
        return image;
      }

首先你需要导入

import 'dart:convert';

所以规范化base64字符串

base64.normalize(base64ToNormalize)