A set literal <T>{...} stores unique values. Adding a duplicate is a no-op.

Program

Play the program to add a duplicate and a new color, then read the length.

sets.dart
Replay: real traced execution (multi-file project)
void main() {
  var colors = <String>{'red', 'green'};
  colors.add('red');
  colors.add('blue');
  print(colors.length);
}
  1. colors ← {red, green}

    1void main() {2  var colors = <String>{'red', 'green'};3  colors.add('red');
    values this step{red, green}colors
  2. colors.add('red');

    2var colors = <String>{'red', 'green'};3colors.add('red');4colors.add('blue');
    values this step{red, green}colors
  3. colors ← {red, green, blue}

    3colors.add('red');4colors.add('blue');5print(colors.length);
    values this step{red, green} {red, green, blue}colors
  4. print(colors.length);

    4  colors.add('blue');5  print(colors.length);6}
    output3
    values this step{red, green, blue}colors

Add Unique Colors

  1. Start with red and green.
  2. Adding red again changes nothing.
  3. Adding blue inserts a new unique value.
  4. The final length is 3. | Action | Set contents | | --- | --- | | start | {red, green} | | add red | {red, green} | | add blue | {red, green, blue} |
set literal `<String>{...}` declares an empty-or-seeded set.
uniqueness Adding an existing element does not grow the set.
length `length` reports the number of unique entries.

Exercise: sets.dart

Add a duplicate and a new value to a set, then print the final unique count