将对象转换为可编码对象失败:“Future<dynamic>”的实例

问题描述 投票:0回答:1

我正在尝试从图像文件中获取 Base64 字符串。当我使用以下方法时

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;
  }

它向我显示一个错误:

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

如果我不带 future 来使用它,它会直接传递到下一步,而不转换为 base64 字符串。通常需要时间来转换。

flutter dart base64
1个回答
0
投票

变量

fileImage
似乎与传递给函数的变量
file
不匹配。这可能是导致问题的原因吗?

我很好奇为什么需要在

await
上调用
String
- 这似乎是不必要的。该错误可能是由于
convertBase64()
的调用方式引起的。对于像
Future<T>
这样的异步方法,我建议这样称呼它:

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

此外,正如之前在评论中建议的那样,最好使用

Uri.dataFromBytes()
而不是自己解析编码的字符串。

Future<String> convertBase64(File file) async{
  List<int> imageBytes = file.readAsBytesSync();
  return Uri.dataFromBytes(imageBytes, mimeType: "image/png").toString();
}
© www.soinside.com 2019 - 2024. All rights reserved.