BASE64 string to Image in Flutter

Issue

I have tried decoding BASE64 String to Uint8List

Uint8List _bytes =
    base64.decode('data:image/jpeg;base64,/9j/4AAQ .........');
Image.memory(_bytes);

But getting error as, (Error on character 🙂

Invalid character (at character 5)
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUSEhMVFRUV…

How could I get rid of this issue?

Solution

You’re using URI that contains data after comma as it is defined by RFC-2397. Dart’s Uri class is based on RFC-3986, so you can’t use it. Split the string by comma and take the last part of it:

String uri = 'data:image/gif;base64,...';
Uint8List _bytes = base64.decode(uri.split(',').last);

Example code will useful for beginners ☺️

GestureDetector(
onTap:(){
showDialog(context: context, builder: (context){
var img64 = snapshot.getStudentDetailModel?.courseDetails?.pscPaymetSlip;
final decodestring = base64Decode('$img64'.split(',').last);
Uint8List encodeedimg = decodestring;
  return AlertDialog(
         contentPadding: EdgeInsets.zero,
         content: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                  Container(
                   height:300,
                   decoration: BoxDecoration(
                   image: DecorationImage(
                   fit: BoxFit.cover,
                   image: MemoryImage(encodeedimg))),),],),);
                                      });
                                      },
                   child:Text('View',                                                 textAlign:TextAlign.end),),

Answered By – Igor Kharakhordin

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *