首页 > 解决方案 > 如何获得我用颤振上传到firebase的图片的精确参考

问题描述

这是我上传图片的代码

 Future uploadProfileImage() async {
    final StorageReference profileImageStorageRef =
        FirebaseStorage.instance.ref().child("Profile Images");
    var currentUserPicture = user.uid.toString();
    final StorageUploadTask profileUploadTask = profileImageStorageRef
        .child(currentUserPicture.toString() + ".jpg")
        .putFile(myImage);
    var imageUrl =
        await (await profileUploadTask.onComplete).ref.getDownloadURL();
    setState(() {
      profilePicUrl = imageUrl.toString();
      print("Image name = " + profilePicUrl);
    });
  }

它在我的 Firebase 数据存储中显示的只是“未来”的实例

标签: androidfirebaseflutterfirebase-storage

解决方案


我没有立即看出代码中有什么问题,但是await在一行中有两个语句使得很难快速扫描发生了什么。

我建议像这样重写它:

  Future uploadProfileImage() async {
    var profileImageStorageRef = FirebaseStorage.instance.ref().child("Profile Images");
    var currentUserPicture = user.uid;
    var useImageStorageRef = profileImageStorageRef.child(currentUserPicture + ".jpg")

    var profileUploadTask = useImageStorageRef.putFile(myImage); // start upload in background
    await profileUploadTask.onComplete; // wait for upload to complete
    var imageUrl = await useImageStorageRef.getDownloadURL(); // wait for the download url

    print("Image name = " + profilePicUrl);
    setState(() {
      profilePicUrl = imageUrl.toString();
    });
  }

推荐阅读