Search code examples
firebaseflutterdartfirebase-storage

How can i upload multiple images to firebase in flutter and get all their download urls


Here is my upload function. My desired output is a list of all urls, but it returns an empty list. I have tried different suggested solutions, but all of them have failed.

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

Solution

  • I think you'll need Future.wait to ensure all futures are resolved before continuing:

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