putIfAbsent是否支持多键?如何用产品名、颜色、尺寸作为复合键
当然可以实现这个需求,你需要把产品名称、颜色、尺寸三个字段组合成一个能唯一标识商品的键,这样只有当三者完全匹配时,putIfAbsent才会复用已有条目,否则就添加新的商品条目。下面是两种常用的实现方式:
方法一:拼接字符串作为键
这种方式简单直接,把三个字段拼接成一个唯一字符串作为Map的键:
_items.putIfAbsent( '${product.named}|$cor|$tamanho', // 用分隔符拼接三个字段,避免不同组合出现相同字符串 () => CartItem( name: product.named, price: product.priced, quantity: count, image: product.imaged, cor: cor, tamanho: tamanho, ), );
注意:这里用|作为分隔符,是为了防止字段内容本身包含特殊字符时,出现不同字段组合出相同字符串的情况(比如名称是"a_b"、颜色是"c",和名称是"a"、颜色是"b_c",如果用下划线拼接就会冲突)。
方法二:自定义键类(更规范的类型安全方式)
如果觉得字符串拼接不够优雅,可以定义一个专门的类作为键,重写hashCode和==运算符,确保只有三个字段都相等时才判定为同一个键:
class CartItemKey { final String name; final String cor; final String tamanho; CartItemKey(this.name, this.cor, this.tamanho); @override bool operator ==(Object other) => identical(this, other) || other is CartItemKey && runtimeType == other.runtimeType && name == other.name && cor == other.cor && tamanho == other.tamanho; @override int get hashCode => Object.hash(name, cor, tamanho); }
然后修改putIfAbsent的调用代码:
_items.putIfAbsent( CartItemKey(product.named, cor, tamanho), // 使用自定义类作为键 () => CartItem( name: product.named, price: product.priced, quantity: count, image: product.imaged, cor: cor, tamanho: tamanho, ), );
这种方式类型更安全,不会出现字符串拼接可能的冲突问题,适合复杂业务场景。
内容的提问来源于stack exchange,提问作者Rafael Reis
相关产品推荐
相关产品推荐

