在地图流中等待

问题描述

我有以下信息流:

  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的情况下遇到了麻烦。该怎么办?

解决方法

请执行以下操作:

  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());
    });
  }