You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从List<DocumentReference>正确返回Future<List<Product?>>?

问题根因
  • Dart的forEach方法不会等待异步回调执行完成。你传入的每个async回调都是独立运行的异步任务,外层方法不会等待所有拉取数据的任务完成就直接返回了空数组,固定延迟属于不可靠的临时方案,网络波动时仍会出错。
  • Cubit调用代码存在两个问题:调用异步方法fromProductRefList时没有加await关键字,同时在if代码块内重复声明了同名productList局部变量,导致外层的productList永远是空数组。另外你的加载状态拼写错误loadding应为loading。
修复后的实现

第一步:重写转换方法

推荐使用Future.wait实现,无需引入额外依赖,并发执行所有数据拉取任务,性能更优:

static Future<List<Product?>> fromProductRefList(List<DocumentReference> ref) async {
  // 将每个引用转换为异步任务,统一等待所有任务完成
  final productFutures = ref.map((productRef) async {
    final productDoc = await productRef.get();
    return await Product.fromDocument(productDoc);
  });
  return Future.wait(productFutures);
}

如果你想使用asyncMap实现,需要先在pubspec.yaml引入collection依赖,写法如下:

import 'package:collection/collection.dart';

static Future<List<Product?>> fromProductRefList(List<DocumentReference> ref) async {
  return ref.asyncMap((productRef) async {
    final productDoc = await productRef.get();
    return await Product.fromDocument(productDoc);
  }).toList();
}

第二步:修复Cubit调用代码

void mapProductToState() async {
  emit(state.copyWith(status: MyProductStatus.loading));
  final shop = _shopBloc.state.shop;
  List<Product?> productList = [];

  if (shop.shopProductRef.isNotEmpty) {
    // 加await等待异步方法返回,不要重复声明final
    productList = await Product.fromProductRefList(shop.shopProductRef);
  }

  emit(state.copyWith(
    shop: shop,
    productList: productList,
    status: MyProductStatus.loaded,
  ));
}

内容的提问来源于stack exchange,提问作者Ennis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:54:04