I've an array of string containing 5 image urls. I'm looking out for a way to fetch the image from url, then encode the image as base64 string, and finally insert that to another array.
The solution should work for both mobile and web in flutter. I was digging around for the solution and got some tricks using File.readAsBytes, Image.toBase64String, etc., but none of them worked on my side.
Finally I found the solution using http package
import 'package:http/http.dart' as http;
Future<String> networkImageToBase64(String imageUrl) async {
http.Response response = await http.get(imageUrl);
final bytes = response?.bodyBytes;
return (bytes != null ? base64Encode(bytes) : null);
}
Example:
final imgBase64Str = await networkImageToBase64('IMAGE_URL');
print(imgBase64Str);
This is working perfectly for both mobile and web.