putIfAbsent can have more then one key?

Viewed 28

I have this putIfAbsent, can I have 3 keys in a putIfAbsent? For example _items.putIfAbsent((product.named, color, size)

_items.putIfAbsent((product.named),() => CartItem(
          name: product.named,
          price: product.priced,
          quantity: count,
          image: product.imaged,
          cor: cor,
          tamanho: tamanho,
        ),
      );

I wanted 3 keys to be able to make a selection, if the product doesn't have the same name, size and color. Added a new product to the list (for example, with a different color than the existing product)

1 Answers

What you need is a Set<CartItem> instead of a list with CartItem overriding the == method like this:

@override
bool operator ==(Object other) {
  if (other is! CartItem) return false;
  return this.color == other.color 
    && this.name == other.name
    && this.size == other.size;
}

Of course we need to override the hashCode method aswell (thanks to Randal Schwartz for the remark):

@override
int get hashCode => Object.hash(this.name, this.color, this.size);
}
Related