Dart / Flutter:Firebase和Firestore等待异步循环完成,然后继续

时间:2020-07-04 22:37:52

标签: flutter dart

我正在尝试将图像提交到Firebase存储,然后还将图像的链接提交到我正在“链接”图像的新记录。

我的问题是,如果我将图像添加到数据中,似乎上传不会使其余的firebase活动发生(对我来说这没有意义)。

基本上,当我单击FAB时,应该提交数据。

floatingActionButton: FloatingActionButton(
          child: Icon(Icons.send),

          // SUBMIT THE DATA
          onPressed: () async {
            setState(() {
              // Show the modal spinner until submit is complete
              showSpinner = true;
            });

            // upload images
            List<StorageReference> fileRefs = [];
            for (var image in imageFiles) {
              fileRefs.add(await uploadPic(context, image));
            }

      // When there are images in the imageFiles array then the below part doesn't run
      // but if no images was selected it runs fine, if images are selected they get uploaded
      // to firebase storage, but no record gets added. :(

            _firestore.collection('InspectionPoints').add({
              'project': selectedProject,
              // some other fields
              'user': loggedInUser.email,
              'photoIds': fileRefs.length == 0 ? [] : fileRefs,
              'timestamp': DateTime.now(),
              //'photoIds' : imageFiles;
            });
           
            setState(() {
              // <---------------  this still runs
              clearForm();
              showSpinner = false;
            });
          } // onPressed
          ),

我现在也尝试将获取文件引用放入异步公式中,但这也行不通:

            // upload images
            List<StorageReference> fileRefs = await getFileRefs(context);

新功能:

  Future<List<StorageReference>> getFileRefs(BuildContext context) async {
    List<StorageReference> fileRefs = [];
    for (var image in imageFiles) {
      fileRefs.add(await uploadPic(context, image));
    }
    return fileRefs;
  }

修改:我的实际上传代码:

  Future<StorageReference> uploadPic(BuildContext context, File image) async {
    StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(basename(image.path));
    StorageUploadTask uploadTask = firebaseStorageRef.putFile(image);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    setState(() {
      print('File: ${image.path} uploaded to the cloud');
      showInSnackBar('File: ${image.path} uploaded to the cloud');
    });
    return taskSnapshot.ref;
  }

2 个答案:

答案 0 :(得分:0)

要将图像上传到Firebase存储,您可以使用下面的代码。

Future upLoadImage(_providedFile, String folderName, String imageName) async{
   //_providedFile -> FILE THAT CONTAINS IMAGE
   //folderName -> FOLDER NAME IN FIREBASE STORAGE
   //imageName -> NAME OF THE IMAGE THAT WILL BE SAVED ON FIREBASE STORAGE

  //FILE UPLOAD LOCATION
  //IF YOU DON'T WANT TO ADD IMAGE IN A FOLDER JUST REMOVE
  //".child(folderName)" from the line  
  StorageReference reference = firebasestorage.ref().child(folderName).child('$imageName.jpg');

  StorageUploadTask uploadTask = reference.putFile(_providedFile);  await 

  uploadTask.onComplete;
}

希望这会对您有所帮助。

答案 1 :(得分:0)

您无法将类型StorageReference保存到Firebase云中,并且由于该类型未能提交而导致整个提交失败,但是由于图像是与数据条目分开上传的,因此在数据输入无法提交。

解决方法是通过StorageReference属性将.path转换为字符串。