【发布时间】:2021-08-23 08:45:20
【问题描述】:
我正在尝试创建一种将列表转换为 Future 的方法。
这是我创建的方法。
static Future<List<Product?>> fromProductRefList(
List<DocumentReference> ref) async {
List<Product> shopProductList = [];
ref.forEach((productRef) async {
final productDoc = productRef.get();
final product = await Product.fromDocument(await productDoc);
shopProductList.add(product!);
});
print('shopProductList: $shopProductList');
return shopProductList;
}
并称它为肘,
void mapProductToState() async {
emit(state.copyWith(status: MyProductStatus.loadding));
final shop = _shopBloc.state.shop;
List<Product?> productList = [];
if (shop.shopProductRef.isNotEmpty) {
final productList = Product.fromProductRefList(shop.shopProductRef);
}
emit(state.copyWith(
shop: shop,
productList: productList,
status: MyProductStatus.loaded,
));
}
VScode 没有显示错误,但是当我运行代码时,fromProductRefList 返回空列表。似乎 fromProductRefList 并没有等待 Document 从数据库中实际 get() 并返回。
当我在返回 shopProductList 之前在 fromProductRefList 中添加第二个延迟时,一切都按预期工作。
我已经阅读了关于 stackoverflow 的另一个问题,建议使用 asyncMap(),但我不确定如何在我的情况下应用它。
编辑: 当我添加延迟时,该方法返回没有任何问题。如果没有,它将返回一个空列表
static Future<List<Product?>> fromProductRefList(
List<DocumentReference> ref) async {
List<Product> shopProductList = [];
ref.forEach((productRef) async {
final productDoc = productRef.get();
final product = await Product.fromDocument(await productDoc);
shopProductList.add(product!);
});
await Future.delayed(const Duration(milliseconds: 500));
print('shopProductList: $shopProductList');
return shopProductList;
}
谢谢。
【问题讨论】:
标签: firebase flutter dart google-cloud-firestore