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

Flutter FutureBuilder列表如何过滤相同store id项仅展示首条数据

这个需求完全可以实现,只需在接口返回数据渲染到列表前,先做一次自定义过滤处理即可,具体操作步骤如下:

步骤1:定义Product数据模型

先将接口返回的JSON数据映射为Dart实体类,方便后续操作:

class Product {
  final String? id;
  final int? numericId;
  final String? store;
  final String? name;
  // 其他需要的字段按需添加

  Product({
    this.id,
    this.numericId,
    this.store,
    this.name,
  });

  factory Product.fromJson(Map<String, dynamic> json) {
    return Product(
      id: json['@id'] as String?,
      numericId: json['id'] as int?,
      store: json['store'] as String?,
      name: json['name'] as String?,
    );
  }
}
步骤2:实现过滤逻辑

根据你的需求写对应过滤规则,以下提供两种常用场景的实现:

场景1:仅store为34的商品去重,仅保留第一条,其他店铺的商品全部保留

List<Product> filterStore34Duplicate(List<Product> originList) {
  bool store34Added = false;
  List<Product> filteredList = [];
  for (var product in originList) {
    if (product.store == '34') {
      if (!store34Added) {
        filteredList.add(product);
        store34Added = true;
      }
    } else {
      filteredList.add(product);
    }
  }
  return filteredList;
}

场景2:所有店铺的商品都去重,每个store仅保留第一条商品

List<Product> filterEachStoreFirst(List<Product> originList) {
  Set<String> addedStores = {};
  List<Product> filteredList = [];
  for (var product in originList) {
    final storeId = product.store ?? '';
    if (!addedStores.contains(storeId)) {
      filteredList.add(product);
      addedStores.add(storeId);
    }
  }
  return filteredList;
}
步骤3:在FutureBuilder中使用过滤后的数据渲染列表
FutureBuilder<List<Product>>(
  // 替换为你自己的接口请求方法,返回解析后的原始Product列表
  future: fetchProductListFromApi(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const Center(child: CircularProgressIndicator());
    }
    if (snapshot.hasError) {
      return Center(child: Text('加载失败:${snapshot.error}'));
    }
    if (!snapshot.hasData || snapshot.data!.isEmpty) {
      return const Center(child: Text('暂无商品数据'));
    }
    // 调用过滤方法处理原始数据
    final finalList = filterStore34Duplicate(snapshot.data!);
    // 渲染列表
    return ListView.builder(
      itemCount: finalList.length,
      itemBuilder: (context, index) {
        final product = finalList[index];
        // 替换为你自己的商品项UI
        return ListTile(
          title: Text(product.name ?? '未命名商品'),
          subtitle: Text('店铺ID:${product.store}'),
        );
      },
    );
  },
)

注意事项

  • 示例JSON中store字段为字符串类型(值为"34"而非数字34),判断时注意类型匹配,避免判断失效
  • 如果需要调整保留规则(比如保留store=34最新的一条而非第一条),只需调整过滤逻辑的遍历顺序即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 10:06:06