首页 > 解决方案 > 您如何调用一个未来,然后将该返回值传递给另一个未来以运行?

问题描述

我正在尝试用我的 Android 相机拍照,将该照片上传到 Google Firebase 存储,在存储上获取该图像的可下载 URL,并在 Firestore 上更新用户的照片供稿。如果我只调用 takeImage() 它会获取图像并成功上传到存储。如果我使用虚拟图像 url 调用 _uploadImage,它会正确更新提要。但是我无法将 takeImage 的结果作为参数传递给 _uploadImage()。

void takeAndSave() async {
              url = await takeImage();
              _uploadImage(url);


          }


Future<String> takeImage() async {
    // open camera
    var image = await ImagePicker.pickImage(source: ImageSource.camera);

    // save image to temp storage
    final String fileName = "${Random().nextInt(10000)}.jpg";

    Directory directory = await getApplicationDocumentsDirectory(); // AppData folder path
    String appDocPath = directory.path;



    // copy image to path
    File savedImage = await image.copy('$appDocPath/' + fileName);

    // upload file to Firebase Storage
    final StorageReference ref = FirebaseStorage.instance.ref().child(fileName);
    final StorageUploadTask task = ref.putFile(savedImage);
    String downloadURL = await ref.getDownloadURL();
    url = downloadURL;
    //    _image = image;

    return downloadURL;
}



Future<void> _uploadImage(String url) async {
    final FirebaseUser user = await widget.auth.currentUser();
    String uid = user.uid;
    print('uid = ' + uid);
    print(url);
      // upload URL to Firebase Firestore Cloud Storage

      Firestore.instance.runTransaction((Transaction transaction) async {
        DocumentReference _newPhoto = Firestore.instance.collection('users').document(user.uid);

        await _newPhoto.collection('cards').add({"url" : url});

      });
  }

标签: flutterfuture

解决方案


根据您的代码,它应该可以正常工作,但是您的 takeImage() 方法可能会返回异常。尝试捕获该异常,看看它是否有帮助。

以下引用自https://www.dartlang.org/tutorials/language/futures#async-await

如果 Future-returning 函数以错误完成,您可能希望捕获该错误。异步函数可以使用 try-catch 处理错误:

Future<String> takeImage() async {
  try {
    // Your code
  } catch (e) {
    // Handle error...
  }
}

推荐阅读