简体   繁体   中英

Converting object to an encodable object failed: Instance of 'Future<dynamic>'

I am trying to get base64 string from image file. When I am using following method

Future convertBase64(file) async{
    List<int> imageBytes = fileImage.readAsBytesSync();
    String base64Image = await 'data:image/png;base64,' + base64Encode(imageBytes);
//    print('length of image bytes ${base64Image.length}');
    return base64Image;
  }

It shows me an error :

exception---- Converting object to an encodable object failed: Instance of 'Future<dynamic>'

If I use without future it directly pass to next step without converting to base64 String. It usually takes time to convert.

The variable fileImage doesn't seem to match the variable file passed to the function. Might this be the one causing the issue?

I'm curious on why the need to call await on a String - this seems to be unnecessary. The error might be caused on how convertBase64() was called. For async methods like Future<T> , I suggest calling it like:

convertBase64(imageFile).then((String base64Image) {
  // Handle base64Image 
});

Also, as previously recommended in the comments, it's better to use Uri.dataFromBytes() instead of parsing the encoded String on your own.

Future<String> convertBase64(File file) async{
  List<int> imageBytes = file.readAsBytesSync();
  return Uri.dataFromBytes(imageBytes, mimeType: "image/png").toString();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM