如何使用 Await 等待值



我正在使用Flutter将图像上传到Firebase,并在提交表单时触发了一个函数submit((。提交时,我会验证提交的内容是否准确,然后调用 uploadFile 函数将指定的图片上传到 Firebase 存储并返回网址,我将其设置为 urlForPost。

我想等待这个urlForPost值被设置,然后再触发将其上传到Firebase的submit((函数的其余部分。目前,它为 urlForPost 返回一个空值。如何等待 uploadFile(( 函数加载,以便我可以防止 urlForPost 为空?

void submit() async {
    // First validate form.
    if (this._formKey.currentState.validate()) {
      _formKey.currentState.save();// Save our form now.
      final urlForPost = await uploadFile();

      Firestore.instance
          .collection('posts')
          .document(documentName)
          .collection('collection')
          .add({
        'user': widget.userPoster,
        'post': _data.post,
        'url': urlForPost,
        'timePosted': Timestamp.now(),
      });
      Firestore.instance.collection('current_goals').document(widget.userPoster).collection(widget.goalType).document(widget.goalID).updateData(
        {
          'complete': true,
        }
      );

      Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) => Home()));    }
  }
  String downloadUrl;
  Future<String> uploadFile() async {
    final String rand1 = "${new Random().nextInt(10000)}";
    final String rand2 = "${new Random().nextInt(10000)}";
    final String rand3 = "${new Random().nextInt(10000)}";
    final StorageReference ref = FirebaseStorage.instance.ref().child('${rand1}_${rand2}_${rand3}.jpg');
     await ref.putFile(widget.selectedImage).onComplete.then((val) {
      val.ref.getDownloadURL().then((val) {
        print(val);
        downloadUrl = val; //Val here is Already String
      });
    });
     return downloadUrl;
  }
您也可以

uploadFile方法更改为上传await

您可以使用await使异步调用同步。但是,如果将其与.then()方法混合使用,则可能会无意中使它的某些部分异步。

  Future<String> uploadFile() async {
    final String rand1 = "${new Random().nextInt(10000)}";
    final String rand2 = "${new Random().nextInt(10000)}";
    final String rand3 = "${new Random().nextInt(10000)}";
    // you don't need {} if it's a simple statement, use $stringvar and ${value.toString}
    final StorageReference ref = FirebaseStorage.instance.ref().child('$rand1_$rand2_$rand3.jpg');
    StorageUploadTask task = ref.putFile(imageFile);
    var downloadUrl = await (await task.onComplete).ref.getDownloadURL();
    debugPrint("downloadUrl=$downloadUrl");
    return downloadUrl.toString();
  }

只是一个与您的原始问题无关的建议

使用 3 个随机数,随着时间的推移,您可能会发生碰撞。考虑使用 UUID 包,冲突的可能性要小得多。:)

  Future<String> uploadFile() async {
    final String uuid = uuid.v4(); // v4 is random, v1 is time-based
    final StorageReference ref = FirebaseStorage.instance.ref().child('$uuid.jpg');
    StorageUploadTask task = ref.putFile(imageFile);
    var downloadUrl = await (await task.onComplete).ref.getDownloadURL();
    return downloadUrl.toString();
  }

最新更新