I have a backend based on NodeJS and using mongodb as the database. Images with the field name photo is saved as object Type Buffer. I have successfully sent Images from the app using form data but I am not able to display the image in frontend.
This is the function used to get the data from API
Future<User> userWithId() async {
User result;
try {
final response = await http.get(
'api link',
headers: <String, String>{
'Authorization': 'Bearer $token',
},
);
if (response.statusCode == 200) {
result = User.fromJson(jsonDecode(response.body));
}
} catch (e) {
print(e.toString());
}
return result;
}
This is the fromJson function of the class User. The photo field here returns the image as buffer.
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['_id'] as String ?? "",
email: json['email'] as String ?? "",
// profilePhoto: json["photo"] ?? null,
// profilePhoto: base64.encode(jsonDecode(json["photo"])) ?? null,
);
}
you can use base64Decode method from dart:convert
store your image binary in string format:
factory User.fromJson(Map<String, dynamic> json) {
return User(
...
profilePhoto: json["photo"] ?? null,
...
);
}
and use the following code in UI:
Image.memory(base64Decode(user.profilePhoto))
also, don't forget to add an if statement to check if the photo is null or not
Hope, it helps
json['photo']['data']['data']; By doing this you are getting this error List' is not a subtype of type 'String'. So may be your return type for profilePhoto is String. Change it to dynamic then try again.
Thanks to the great article bellow explaining about bytes in dart, you can convert your response data which is as List of integers, to Uint8List data type and pass it to Image.memory to render image.
Image.memory(Uint8List.fromList(// pass image data array here));
https://medium.com/flutter-community/working-with-bytes-in-dart-6ece83455721