使用flutter将多张图片上传到Firestore并获取其下载URL并将所有URL保存到Firebase

时间:2019-12-23 11:36:28

标签: firebase flutter async-await firebase-storage

我有一个要上传图像的表单,当用户尝试按“提交”按钮时,我试图将图像列表上传到firestore并获取其所有URL,然后将表单提交给“ x”在Firebase中进行了收集,但是在上传图像并获取URL之前完成了“ x”搭配的编写。

我认为(async,await)有问题。

感谢帮助我。

List<File> imagePaths= new List() ;
List<String> imageURL= new List() ;

Future<FirebaseUser> getUser() async {
    return await _auth.currentUser();
}

Future<void> uploadPic(File _image) async {

    String fileName = basename(_image.path);
    StorageReference firebaseStorageRef = 
    FirebaseStorage.instance.ref().child(Random().nextInt(10000).toString()+fileName);
    StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
    var downloadURL = await(await uploadTask.onComplete).ref.getDownloadURL();
    var url =downloadURL.toString();
    imageURL.add(url); // imageURL is a global list that suppose to contain images URLs
    print("\n ---------------------------\n downloadURL :"+ url);
    print("\n ---------------------------\n imageURL :"+ imageURL.toString());

  }


Submit(BuildContext context)   {
    //imagePaths is list of file 
    imagePaths.add(Front_image);
    imagePaths.add(Back_image);

    imagePaths.forEach((x)  => {
       uploadPic(x)
    });


    getUser().then((user) {

      crudObj.addNew({
        'uid': user.uid,
        'name': name,
        'images':imageURL,
      }).then((result) {
        Navigator.pop(context);

      }).catchError((e) {
        print(e);
      });
    });

  }

1 个答案:

答案 0 :(得分:0)

仅当完成上传任务后,才应调用“提交”。我建议实施这样的内容:

Stream uploadImageToFirebaseStorage(File image, String fullPath) {
  final StorageReference firebaseStorageRef =
      FirebaseStorage.instance.ref().child(fullPath);
  StorageUploadTask task = firebaseStorageRef.putFile(image);

  return task.events;
}

然后收听此流,然后才提交:

uploadImageToFirebaseStorage(
  image, 'path/imagename.jpg'
).listen((data) async {
  StorageTaskEvent event = data;
  if (data.type == StorageTaskEventType.success) {
    String downloadUrl = await event.snapshot.ref.getDownloadURL();
    await Submit(title, imageUrl: downloadUrl);
    return true;
  }
  if (data.type == StorageTaskEventType.failure) return false;
});

请注意,我没有重写您的代码,我正在共享一个可能的实现。