如何使用Await等待值

问题描述 投票:0回答:1

我正在使用Flutter将图像上传到Firebase,并且在我提交表单时会触发一个函数submit()。提交时,我验证提交是否准确,我调用uploadFile函数将指定的图像上传到Firebase存储并返回URL,我将其设置为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;

  }
flutter
1个回答
0
投票

您也可以将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();
  }

just a suggestion unrelated to your original question

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

  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();
  }
© www.soinside.com 2019 - 2024. All rights reserved.