4

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.

2
  • 1
    might be helpful stackoverflow.com/questions/50036393/… Commented Mar 6, 2020 at 13:54
  • @AR Thanks but I've already visited the link you provide. The solution proposed there isn't working as I mentioned in the question. Commented Mar 6, 2020 at 14:06

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It works but then crashs with an error 36 - File name is too long.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.