【问题标题】:(Flutter/Dart) Retrieve from Firebase storage while retrieving from Firebase Firestore, async within async(Flutter/Dart) 从 Firebase 存储中检索,同时从 Firebase Firestore 中检索,异步中的异步
【发布时间】:2021-03-27 11:40:40
【问题描述】:

我正在尝试根据从 Firebase Firestore 中检索到的文档 ID 从 Firebase 存储中检索图像。我遇到了一个问题,因为这些实例中的每一个都返回一个 Future 并且需要一个单独的等待/异步。

我不能使用Future.wait(),因为我需要 Firestore 中的第一个异步来进行第二个异步,但我还需要在第一个异步完成之前启动第二个异步(我知道这不是异步的工作方式)。我尝试在一个表现正常的异步函数中创建一个异步函数(外部异步首先运行,内部异步运行第二)。

static Future<List<Recipe>> getFirebaseRecipes() async {
    CollectionReference recipesDatabase = FirebaseFirestore.instance.collection('recipes');

    List<Recipe> recipes = new List();
    recipesDatabase.get().then((querySnapshot) => querySnapshot.docs.map((doc) async {
      Reference ref = FirebaseStorage.instance.ref().child('recipeimages');
      String url = await ref.child(doc.id + '.jpg').getDownloadURL();
      recipes.add(Recipe.fromDBMap(doc.id, url, doc.data()));
    }));
        
    return recipes;
}

这是我希望能够做到的,但显然不能使用它,因为第二个没有异步功能:

static Future<String> getImageURL(String dbId) async {
    Reference ref = FirebaseStorage.instance.ref().child('recipeimages');
    return await ref.child(dbId + '.jpg').getDownloadURL();
  }

static Future<List<Recipe>> getFirebaseRecipes() async {
    CollectionReference recipesDatabase = FirebaseFirestore.instance.collection('recipes');

    return recipesDatabase.get().then((querySnapshot) => querySnapshot.docs.map((doc) => Recipe.fromDBMap(doc.id, await getImageURL(doc.id), doc.data), doc.data())).toList());
  }

如果有人对如何从 Firebase 存储中检索对象(甚至如何在 Firestore 中存储和映像)有任何提示或其他方法,我将不胜感激!

【问题讨论】:

  • 上传完成后为什么不将图片下载 URL 存储到其文档中,这样您就不必每次都查询来获取其 URL
  • 为什么你不能使用第一个sn-p?
  • @PeterHaddad 我尝试使用它,但它在第二次等待完成之前完成执行,因此它在返回后将对象添加到列表中。

标签: firebase flutter dart google-cloud-firestore async-await


【解决方案1】:

尝试以下方法:

static Future<List<Recipe>> getFirebaseRecipes() async {
    CollectionReference recipesDatabase = FirebaseFirestore.instance.collection('recipes');

    List<Recipe> recipes = new List();
    var querySnapshot = await recipesDatabase.get();
      querySnapshot.docs.map((doc) async {
        Reference ref = FirebaseStorage.instance.ref().child('recipeimages');
        String url = await ref.child(doc.id + '.jpg').getDownloadURL();
        recipes.add(Recipe.fromDBMap(doc.id, url, doc.data()));
     }));   
    return recipes;
}

您需要使用await等待firestore从数据库中检索所有数据,然后您可以使用结果获取下载地址。

【讨论】:

  • 嗯我试过这个它也没有执行内部的等待。我最终只是将存储连接到 Firestore,因此只需要一个异步函数。
猜你喜欢
  • 2018-02-19
  • 2017-01-11
  • 1970-01-01
  • 1970-01-01
  • 2016-02-16
  • 2023-03-03
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
相关资源
最近更新 更多