Reputation: 288
I am few months into Flutter, Ran into this issue where I have gotten a base64 String from an API, I have decoded the base 64 string and converted it to bytes. When I try to display it on an image widget I get nothing. Below is my code. and a snippet from my console. Thank you.
if (imgString != null) {
_bytesImage = base64.decode(imgString.toString());
print(_bytesImage);
return ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Image.memory(
_bytesImage,
width: 300,
height: 250,
fit: BoxFit.cover,
));
} else {
print("Image String is null");
return SizedBox.shrink();
}
Upvotes: 0
Views: 1264
Reputation: 26
I had the same issue. I just did this.
Added this under Build Widget.
I stored the base64 string in var called _imgString. It was containing some new line characters in it. So I used split function and joined them to get a proper format.
Uint8List _image = base64.decode(_imgString.split('\n').join());
image = Image.memory(
_image,
fit: BoxFit.cover,
);
You can call this image object in your widget tree wherever you want.
For eg.
Container(
margin: const EdgeInsets.all(15.0),
padding: const EdgeInsets.all(3.0),
height: 250.0,
width: 400,
child: SingleChildScrollView(
// for Vertical scrolling
scrollDirection: Axis.vertical,
child: image,
),
),
Upvotes: 1
Reputation: 1430
You can convert a Uint8List to a Flutter Image..
if (imgString != null) {
_bytesImage = BASE64.encode(imgString.toString());
Uint8List bytes = BASE64.decode(_bytesImage);
print(bytes);
return ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Image.memory(
bytes,
width: 300,
height: 250,
fit: BoxFit.cover,
));
} else {
print("Image String is null");
return SizedBox.shrink();
}
Upvotes: 0