Flutter Firestore查询2个集合

zee*_*zee 5 dart firebase flutter google-cloud-firestore

问题已更新

\n\n

我如何\xc2\xa0查询2个集合?I\xc2\xa0 有一个愿望清单集合,其中每个愿望清单文档如下所示:

\n\n
documentID: "some-wishlist-id",\nmodified: "1564061309920",\nproductId: "2tqXaLUDy1IjxLafIu9O",\nuserId: "0uM7Dt286JYK6q8iLFyF4tG9cK53"\n
Run Code Online (Sandbox Code Playgroud)\n\n

还有一个产品集合,其中每个产品文档如下所示。愿望清单集合中的 ProductId 将是产品集合中的 documentID\xc2\xa0:

\n\n
documentID: "2tqXaLUDy1IjxLafIu9O",\ndateCreated: "1563820643577",\ndescription: "This is a description for Product 9",\nimages: ["some_image.jpg"],\nisNegotiable: true,\nisSold: false,\nrentPrice: 200,\nsellPrice: 410,\ntitle: "Product 9",\ntotalWishLists: 0,\nuserId: "0uM7Dt286JYK6q8iLFyF4tG9cK53"\n
Run Code Online (Sandbox Code Playgroud)\n\n

注意:需要明确的是,愿望清单查询应该返回我需要迭代以检索产品的文档列表。

\n\n

不确定在这种情况下 I\xc2\xa0 是否需要使用流或 future,但这就是我到目前为止所拥有的:

\n\n
Future<Product> getProduct(String documentId) {\nreturn Firestore.instance\n    .collection(APIPath.products())\n    .document(documentId)\n    .get()\n    .then((DocumentSnapshot ds) => Product.fromMap(ds.data));\n}\n\nQuery getWishListByUser(userId) {\n    return Firestore.instance\n        .collection(APIPath.wishlists())\n        .where(\'userId\', isEqualTo: userId);\n}\n\nFuture<List<Product>> getProductsWishList(userId) async {\n    List<Product> _products = [];\n\n    await getWishListByUser(userId)\n        .snapshots()\n        .forEach((QuerySnapshot snapshot) {\n      snapshot.documents.forEach((DocumentSnapshot snapshot) async {\n        Map<String, dynamic> map = Map.from(snapshot.data);\n        map.addAll({\n          \'documentID\': snapshot.documentID,\n        });\n\n        WishList wishList = WishList.fromMap(map);\n\n        await getProduct(wishList.productId).then((Product product) {\n          print(product.title); // This is printing\n          _products.add(product);\n        });\n      });\n    });\n\n    // This is not printing\n    print(_products);\n\n    return _products;\n  }\n
Run Code Online (Sandbox Code Playgroud)\n\n

谢谢

\n

zee*_*zee 2

我上周末找到了解决方案,但忘了发布。我想我现在就这样做,以防其他人遇到这个问题。

StreamBuilder我使用了和的组合FutureBuilder。不确定是否有更好的答案,也许组合多个流?但这对我有用。

return StreamBuilder<List<Wishlist>>(
  stream: wishListStream(userId),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      List<Wishlist> wishlists = snapshot.data;

      if (wishlists.length > 0) {
        return new GridView.builder(
          scrollDirection: Axis.vertical,
          itemCount: wishlists.length,
          itemBuilder: (context, index) {
            Future<Product> product =
                getProduct(wishlists[index].productId);

            return FutureBuilder(
              future: product,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  Product product = snapshot.data;

                  // Do something with product
                } else {
                  return Container();
                }
              },
            );
          },
          gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
          ),
        );
      } else {
        return Text('No products in your wishlist');
      }
    }

    if (snapshot.hasError) {
      print('WishlistPage - ${snapshot.error}');
      return Center(child: Text('Some error occurred'));
    }

    return Center(child: CircularProgressIndicator());
  },
);
Run Code Online (Sandbox Code Playgroud)