ref.getDownloadURL在上传时为null,如何等待将其放入其他变量

时间:2019-06-28 08:11:14

标签: firebase flutter dart firebase-storage

我正在尝试将图像上传到Firebase存储,然后将下载URL放在Firebase云Firestore中,但是数据库中的值始终为空

File image;
String imageUrl;

...

  Future<Null> uploadImage() async {
    if (image == null) {
      imageUrl = defaultImage;
    } else {
      StorageReference ref = FirebaseStorage.instance.ref().child(filename);
      uploadTask = ref.putFile(image);

      imageUrl = await (await uploadTask.onComplete).ref.getDownloadURL();
    }
  }

  void _addData() {
    Firestore.instance.collection('kajian').add({
      "imageUrl": imageUrl,
    });
    image = null;
    imageUrl = null;
  }

...

      Scaffold(
        floatingActionButton: new FloatingActionButton(
          onPressed: () {
            uploadImage();
            _addData();
            Navigator.pop(context);
          },
          child: Icon(Icons.cloud_upload),
        ),

1 个答案:

答案 0 :(得分:0)

仅在图像上传完成后才能确定下载URL。因此,上传完成后,您必须将其写入数据库。

Future<Null> uploadImage() async {
  StorageReference ref = FirebaseStorage.instance.ref().child(filename);

  uploadTask = ref.putFile(image);

  String imageUrl = await (await uploadTask.onComplete).ref.getDownloadURL();

  Firestore.instance.collection('kajian').add({
    "imageUrl": imageUrl,
  });
}