【问题标题】:async image upload in flutter for multiple images to firebase storage将多个图像的异步图像上传到firebase存储
【发布时间】:2021-10-14 08:44:31
【问题描述】:

我正在尝试将多张图片上传到 Firebase 存储。我遇到的问题是尝试检索每个图像的 URL。如果我不尝试检索 URL,文件本身会成功上传,我看到的问题是上传与生成的 url 并行运行,因此在到达第二张图像时没有更新 url。

我得到的错误是“[firebase_storage/object-not-found] 在所需的引用处不存在对象。”

注意:我没有使用 forEach,因为我将要上传的文件数限制为 5。下面的代码包含在 if 语句中以检查列表长度。

 for (var i = 0; i < _imageFileList!.length; i++) {

               if (kIsWeb) {

                var bytes = await _imageFileList![i].readAsBytes();

                print('photo$i');


                Reference snapshot =  await FirebaseStorage.instance.ref().child('items/$itemkey/photo$i');

                UploadTask uploadFile = snapshot.putData(bytes);

// If I delete the following 2 lines then the uploadof multiple files works without any issues.

                  imagesUrls.add(await (snapshot.getDownloadURL()));

                  print(imagesUrls);

/////    /////    /////    /////    /////    /////

              } else {

                String filePath = 'items/${itemkey}/photo${i}.jpg';

                Reference snapshot = FirebaseStorage.instance.ref().child(filePath);

                UploadTask uploadFile = snapshot.putFile(File(_imageFileList![i].path));

// currently doesnt work but testing on web so this doesnt trigger.

                final String downloadUrl = await snapshot.getDownloadURL();

                print(downloadUrl);

//////////////////////////////////
              }


            }

如何让这些运行异步或等待?我不能将 await 放在 for 循环前面,因为颤动告诉我我不能将 await 用于正常的 for 循环。

【问题讨论】:

    标签: flutter for-loop firebase-storage


    【解决方案1】:

    我在不正确的语句上使用了 await 函数。为了实现上述目的,await 应该位于上传任务的下一行,并且应该包含在“.then”语句中。下面是解决方案

    Reference snapshot =  FirebaseStorage.instance.ref().child('items/$itemkey/photo$i');
    
                    await snapshot.putData(bytes).then((value) async{
    
                      imagesUrls.add(await (snapshot.getDownloadURL()));
                      //
                      print(imagesUrls);
    
    
                    });
    

    【讨论】:

      猜你喜欢
      • 2017-09-25
      • 2018-10-24
      • 2019-01-22
      • 2018-06-10
      • 2022-11-11
      相关资源
      最近更新 更多