如何在 flutter 中将多个图像上传到 firebase 并获取它们的所有下载网址

Bri*_*ht 4 dart firebase flutter firebase-storage

这是我的上传功能。我想要的输出是所有网址的列表,但它返回一个空列表。我尝试了不同的建议解决方案,但都失败了。

Future<List<String>> uploadFiles(List _images) async {
  List<String> imagesUrls=[];

   _images.forEach((_image) async{
    StorageReference storageReference = FirebaseStorage.instance
        .ref()
        .child('posts/${_image.path}');
    StorageUploadTask uploadTask = storageReference.putFile(_image);
    await uploadTask.onComplete;

     imagesUrls.add(await storageReference.getDownloadURL());
     
  });
print(imagesUrls);
return imagesUrls;
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*len 18

我认为您需要Future.wait确保所有未来都得到解决,然后才能继续:

Future<List<String>> uploadFiles(List<File> _images) async {
  var imageUrls = await Future.wait(_images.map((_image) => uploadFile(_image)));
  print(imageUrls);
  return imageUrls;
}

Future<String> uploadFile(File _image) async {
  StorageReference storageReference = FirebaseStorage.instance
      .ref()
      .child('posts/${_image.path}');
  StorageUploadTask uploadTask = storageReference.putFile(_image);
  await uploadTask.onComplete;

  return await storageReference.getDownloadURL();
}
Run Code Online (Sandbox Code Playgroud)