DartBasic 2 min read

Dart sets and maps: deduplicate tags and count stock

Use set membership and typed map updates for a practical stock summary.

On this page

A product can appear more than once in a sales import. A set answers whether a value has appeared; a map associates a key with a value. Neither should be used as a substitute for a domain model when several independent fields belong together.

Worked example

Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.

main.dart
void main() {
  final scanned = ['cable', 'mouse', 'cable', 'cable'];
  final unique = scanned.toSet();
  final counts = <String, int>{};
  for (final sku in scanned) {
    counts.update(sku, (count) => count + 1, ifAbsent: () => 1);
  }
  print('Unique: ${unique.join(', ')}');
  print('Cable count: ${counts['cable']}');
  print('Unknown count: ${counts['monitor'] ?? 0}');
}

Follow the data and control flow

The set holds two unique identifiers. Each map update increments an existing count or inserts the first count through ifAbsent. Map lookup is nullable because a key may not exist; ?? 0 is an intentional display fallback here.

Distinguish a missing key from a key whose value is null when you use nullable map values. Use containsKey when that distinction is meaningful. For custom object keys, consistent equality and hash codes are part of correctness; the object-design chapter explains that boundary.

A mistake to avoid

Normalizing identifiers with lowercase is appropriate only if the identifier contract is case-insensitive. Do not merge two genuinely different SKUs just to make a count look tidy. Avoid storing a changing mutable field as a map key through a custom hash implementation.

Practice and verification

Print all SKU/count entries, then find those with a count above one. Add an explicit normalizer for a case-insensitive import and test it separately. Explain why a map of counts loses the original sequence of individual scans.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.