如何从Dart的Products类商品数据中提取分类生成新列表
实现方案
先修正你现有代码里的两个小问题:
- 原
itemsgetter 逻辑错误,return [...items]会触发无限递归调用,应修改为return [..._productItems] - 你定义的
categoriesListgetter 类型错误,分类列表存储的是字符串值,返回类型应为List<String>而非List<Product>
核心实现代码
你可以通过遍历商品列表提取分类字段,再转Set去重的方式生成目标列表:
class Products with ChangeNotifier { List<Product> _productItems = [ Product( id: 'p1', title: 'Red Shirt', price: 29.99, category: 'shirts', ), Product( id: 'p2', title: 'Trousers', description: 'A nice pair of trousers.', price: 59.99, category: 'Trousers', ), Product( id: 'p3', title: 'Yellow Scarf', price: 19.99, category: 'Scarfs', ), Product( id: 'p4', title: 'A Pan', price: 49.99, category: 'Pans', ), ]; List<Product> get items { // 修正递归错误 return [..._productItems]; } List<Product> get fovoriteItems { return _productItems.where((prodItem) => prodItem.isFavorite!).toList(); } List<Product> get stockItems { return _productItems.where((prodItems) => prodItems.isStock!).toList(); } // 分类列表实现 List<String> get categoriesList { // 提取所有商品的category字段,转Set自动去重后转回List return _productItems.map((prod) => prod.category).toSet().toList(); } // 如果你需要统一分类首字母大写的格式(匹配你示例的输出格式),可以用下面的实现替换上面的getter // List<String> get categoriesList { // return _productItems.map((prod) { // String category = prod.category; // if (category.isEmpty) return category; // return category[0].toUpperCase() + category.substring(1); // }).toSet().toList(); // } }
实现说明:
- 调用
map方法遍历所有商品实例,提取每个实例的category字段,得到分类的Iterable集合 - 调用
toSet()方法自动去除重复的分类值,避免同一个分类出现多次 - 最后调用
toList()将Set转为List格式,得到最终的分类列表
内容的提问来源于stack exchange,提问作者Muhammad Tawil
相关产品推荐
相关产品推荐

