imageflutterdartbase64

Flutter: Base64: Invalid length, must be multiple of four (FormatException)


I got image Base64 encoded image data, but one of the images I got was not uploaded and gives an error in the form of

invalid length must be multiple of four.

Also, my other images appear for a moment and then disappear for a moment. They come and go. Is there a solution for this issue?

     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,
                      ),
                    ],
                  ),

Solution

  • You need to pad the Base64 string with one or two "=" to reach a length that is a multiple of 4.

    If it can be divided by 4 without rest, it's fine. If the remainder of length modulo 4 is 3, you add 1 '=' and if the remainder is '2 you add 2 '=' to the string.

    In dart you get the length of a string with "".length and then calculate the remainder of a division by 4 with the modulo operator %:

    As the actual problem turned out to be a null string, the following code also checks for null or empty strings and shows a placeholder image instead of an error message.

    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;
          }