首页 > 解决方案 > 如何将图像从 Firebase 云存储加载到颤动

问题描述

我已将图像存储在 Firebase Cloud Storage 上,我想将它们放在图标上。我想要一个函数来传递图像的名称并为我获取该图像的 URL,但这种方法对我不起作用。

Future<String> downloadURLExample(product) async {
    String downloadURL = await firebase_storage.FirebaseStorage.instance
        .ref('product_images/fruits/$product.jfif')
        .getDownloadURL();
    return downloadURL;
  }
  
  String returnImg(String product){
    downloadURLExample(product).then((value) => {
      imgURL = value
    });
    return imgURL;
  }

我这样称呼我的函数:

returnImg(apple)

标签: firebaseflutterdartgoogle-cloud-storage

解决方案


您应该使用await异步功能:

await downloadURLExample(product);

这是完整的例子:

Future<String> downloadURLExample(product) async {
    String downloadURL = await firebase_storage.FirebaseStorage.instance
        .ref('product_images/fruits/$product.jfif')
        .getDownloadURL();
    return downloadURL;
  }
  
  String returnImg(String product) {
    String imgURL = await downloadURLExample(product);
    return imgURL;
  }

您可以按如下方式调用该函数:

returnImg('apple');

您可以在此处async阅读有关函数的更多信息。


推荐阅读