user13182526
user13182526

Reputation: 47

Flutter/Dart - Convert image(base64) show error in circle avatar

Convert the image get in to :

final prefs = await SharedPreferences.getInstance(); 
var image = ((prefs.getString('photo'))); 
var send = {'name': usu, 'email': email, 'image': photo};

In widget:

Widget _buildDrawer(BuildContext context) { return FutureBuilder<Map>(
      future: getFutureDates(), // function where you call your api
      builder: (BuildContext context, AsyncSnapshot<Map> snapshot) {
    if(!snapshot.hasData) {
      return Center(child: CircularProgressIndicator());
    } else {
      Uint8List profile = base64.decode(snapshot.data['image']); new UserAccountsDrawerHeader(
                  accountName: new Text((json.encode(snapshot.data['name']).toString().replaceAll('"', ''))),
                  accountEmail: new Text((json.encode(snapshot.data['email']).toString().replaceAll('"', ''))),
                  currentAccountPicture: new CircleAvatar(
                    backgroundImage: MemoryImage((profile)),
                  ),
                ), } }

The Name and email is ok, but Photo give me a error:

Invalid character (at charact er 5)

data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBw8PDw8PDxAPDw4PD...

Upvotes: 0

Views: 2202

Answers (1)

chunhunghan
chunhunghan

Reputation: 54367

Reason:

base64 string contains data:image/png;base64, cause error

data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBw8PDw8PDxAPDw4PD

Solution:

remove string data:image/png;base64, , you can use substring(22) and only keep

/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBw8PDw8PDxAPDw4PD...

code snippet

void main() { 
  String base64str = '''data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBw8PDw8PDxAPDw4PD''';
  String newString =  base64str.substring(22);      
  print(newString);

}

output

/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBw8PDw8PDxAPDw4PD    

Upvotes: 1

Related Questions