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

Flutter:如何基于分类列表的索引对产品列表排序

基于分类索引对产品列表排序的实现方案

核心思路

先把分类数据转换成分类ID到排序索引的映射表,再通过这个映射表快速匹配产品对应的排序值,最终完成产品列表的排序。


1. 构建分类排序映射表

从Firestore获取分类数据后,将其转换成以categoryID为键、index(转为整数,方便数值比较)为值的Map,这样后续排序时能以O(1)的效率获取排序依据。

// 从Firestore获取的分类数据示例
List<Map<String, dynamic>> categoryList = [
  {"index": "0", "categoryName": "Drinks", "categoryID": 1234},
  {"index": "1", "categoryName": "Cake", "categoryID": 1235}
];

// 构建分类ID到排序索引的映射
Map<int, int> categorySortMap = {};
for (var category in categoryList) {
  int categoryId = category['categoryID'];
  int sortIndex = int.parse(category['index']);
  categorySortMap[categoryId] = sortIndex;
}

2. 对产品列表执行排序

使用List.sort()方法,根据每个产品的categoryID从映射表中取出对应的排序索引,以此作为排序标准。对于找不到对应分类的产品,可以设置默认值(比如放到列表末尾)。

// 原始产品列表示例
List<Map<String, dynamic>> products = [
  {"name": "Milk Shake Strawberry", "price": "250", "category": "Drinks", "categoryID": 1234},
  {"name": "Swiss Roll", "price": "150", "category": "Cake", "categoryID": 1235}
];

// 按分类索引升序排序
products.sort((a, b) {
  // 无匹配分类的产品默认排最后,用9999作为默认索引
  int aSortIndex = categorySortMap[a['categoryID']] ?? 9999;
  int bSortIndex = categorySortMap[b['categoryID']] ?? 9999;
  return aSortIndex.compareTo(bSortIndex);
});

3. 结合Firestore数据的完整流程

因为分类和产品数据都存在Firestore,需要确保两者都获取完成后再执行排序,可通过Future.wait()并行获取两个集合的数据:

Future<void> fetchAndSortProducts() async {
  // 并行获取分类和产品集合数据
  final categorySnapshot = await FirebaseFirestore.instance.collection('categories').get();
  final productSnapshot = await FirebaseFirestore.instance.collection('products').get();

  // 转换为可操作的列表
  List<Map<String, dynamic>> categoryList = categorySnapshot.docs.map((doc) => doc.data()).toList();
  List<Map<String, dynamic>> products = productSnapshot.docs.map((doc) => doc.data()).toList();

  // 构建排序映射表
  Map<int, int> categorySortMap = {};
  for (var category in categoryList) {
    categorySortMap[category['categoryID']] = int.parse(category['index']);
  }

  // 执行排序
  products.sort((a, b) {
    int aSortIndex = categorySortMap[a['categoryID']] ?? 9999;
    int bSortIndex = categorySortMap[b['categoryID']] ?? 9999;
    return aSortIndex.compareTo(bSortIndex);
  });

  // 更新UI,比如将排序后的列表赋值给状态变量
  // setState(() => sortedProducts = products);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:40:21