android - 未来> 迭代图像列表时返回 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]
问候,非常感谢!
解决方案
填充列表的代码是异步的:imagesToBase64.add(await utils.imageToBase64(imageFile));
但是您无需等待异步计算完成就返回列表。基本上,return imagesToBase64;
在向其添加任何值之前调用,因此为空。尝试这样的事情:
return Future.forEach(_images, (File imageFile) async {
imagesToBase64.add(await utils.imageToBase64(imageFile));
}).then((_) => imagesToBase64);
推荐阅读
- python - OSMNX - 边缘的哪个“部分”被认为是最近的
- python - os.PathLike[Any] vs os.PathLike[str]
- jquery - 发送对象作为函数参数
- javascript - React Native Bundle 下载屏幕
- ios - 有关带有 Outlook iOS 应用附件的邮件的任何文档
- javascript - 应用于列表的 jquery 选择器“:checked”的简写
- linux - 增加 Google Cloud Shell 超时时间?
- r - 编写一个进度条函数以在 R 的循环中调用
- data-modeling - 软删除中的 Deleted_Flg 和有效结束日期
- matlab - 如何使用求解函数来求解向量而不是标量