> 迭代图像列表时返回 null,android,ios,flutter,dart"/>

首页 > 解决方案 > 未来> 迭代图像列表时返回 null

问题描述

我需要得到 transformPhotos 函数的结果,它应该给我一个 base64 中的图像列表(它确实)但是当我在下一个函数中得到它时它会抛出 []

Future<List<String>> transformPhotos() async {
  List<String> imagesToBase64 = [];
  if (_images.length > 0) {
    _images.forEach((File imageFile) async {
      imagesToBase64.add(await utils.imageToBase64(imageFile));
    });
  }
  return imagesToBase64;
}
Future<void> uploadPhotos() async {
  transformPhotos().then((onValue) {
    print(onValue); //throws []
  });
}

我希望得到如下结果:[String, String, String]

问候,非常感谢!

标签: androidiosflutterdart

解决方案


填充列表的代码是异步的:imagesToBase64.add(await utils.imageToBase64(imageFile));

但是您无需等待异步计算完成就返回列表。基本上,return imagesToBase64;在向其添加任何值之前调用,因此为空。尝试这样的事情:

return Future.forEach(_images, (File imageFile) async {
  imagesToBase64.add(await utils.imageToBase64(imageFile));
}).then((_) => imagesToBase64);

推荐阅读