首页 > 解决方案 > 上传时ref.getDownloadURL为null,如何等待才能将其放入其他变量

问题描述

我正在尝试将图像上传到 firebase 存储,然后将下载 URL 放入 firebase 云 firestore,但数据库中的值始终为 null

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),
        ),

标签: firebaseflutterdartfirebase-storage

解决方案


只有在图片上传完成后才能确定下载 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,
  });
}

推荐阅读