【问题标题】:await in map in a stream在流中的地图中等待
【发布时间】:2020-12-01 13:53:44
【问题描述】:

我有以下流:

  Stream<List<Product>> products() {
    //Get Products from Cloud Firestore
    return productCollection.snapshots().map((snapshot) {
      return snapshot.documents.map((document) {
        //Get image metadata of each product from Firebase Storage
        Future<StorageMetadata> _metadata = imageRef
            .child('${document.documentID}/${document.data['mainImage']['name']}')
            .getMetadata()
            .catchError((onError) => print('Error: $onError'));
        //After getting metadata, create product objects with data gathered above
        return Product.fromEntity(ProductEntity.fromSnapshot(
            document, ProductImageEntity.fromMetadata(_metadata)));
      }).toList();
    });
  }

我需要在从 Firebase 存储中检索元数据之后返回产品对象。我是异步编程的新手,并且在不将流返回类型更改为 Future 的情况下无法做到这一点。如何做到这一点?

【问题讨论】:

  • 你可能想看看asyncMap
  • @Irn asyncMap 只能应用于快照流。我需要在地图中等待文档列表以获取元数据。你能澄清一下 asyncMap 在这里如何使用吗?

标签: dart google-cloud-firestore firebase-storage


【解决方案1】:

通过以下方式做到了:

  Stream<List<Product>> products() {
    //Get Products from Cloud Firestore
    return productCollection.snapshots().asyncMap((snapshot) {
      return Future.wait(snapshot.documents.map((document) async {
        //Get image metadata of each product from Firebase Storage
        StorageMetadata _metadata = await imageRef
            .child(
                '${document.documentID}/${document.data['mainImage']['name']}')
            .getMetadata()
            .catchError((onError) => print('Error: $onError'));
        //After getting metadata, create product objects with data gathered above
        return Product.fromEntity(ProductEntity.fromSnapshot(
            document,
            ProductImageEntity.fromMetadata(_metadata),
        ));
      }).toList());
    });
  }

【讨论】:

    猜你喜欢
    • 2020-09-12
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 2011-12-13
    • 2020-05-16
    相关资源
    最近更新 更多