Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASE64 string to Image in Flutter

Tags:

flutter

dart

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?

like image 538
Kavin-K Avatar asked Dec 11 '22 01:12

Kavin-K


1 Answers

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),),
like image 77
Igor Kharakhordin Avatar answered Jan 14 '23 18:01

Igor Kharakhordin