Dart, lesson 7
One variable per value stops working once you have a class of 30 students or a week of
temperatures. Collections hold many values under one name. Dart's three everyday
collections are List, Set and Map.
A List is an ordered sequence. Write one with square brackets:
final here means the variable always points to the same list; you can still add to and
change the list itself. Reading an index that doesn't exist (like scores[10]) stops the
program with a RangeError, so check length when unsure.
Useful list tools:
sort() can take a comparison function to change the order.
sorts from largest to smallest.
2 exercises to try what you just read.
(a, b) => b.compareTo(a)An empty list needs its type spelled out, because Dart can't infer it from nothing:
final names = <String>[];.
A Set holds unique values, with no duplicates. Adding something that's already there does
nothing:
Sets are great for "have I seen this before?" questions. An empty set is written
<String>{}, since a bare {} means an empty map.
A Map connects keys to values, like a dictionary connects words to definitions:
Because a key might be missing, stock['x'] has a nullable type (int?). Handle it with
?? or check with containsKey first:
Counting things is a classic map job. update changes an existing value, and ifAbsent
supplies the first one:
Dart's default maps remember the order keys were first added, so looping over them gives a predictable order:
That MapEntry(:key, :value) is a pattern that pulls both parts out of each entry at once.
counts.keys and counts.values give you just one side.
Read one line of game scores separated by spaces. Print how many scores there are, the best
score, and then all scores from highest to lowest separated by , . There is always at least
one score.
Input:
Output:
Birdwatchers log each sighting on its own line. Read lines until the input runs out and
count how many times each bird was seen. Print one line per bird, in the order each bird was
first seen, as bird: count. Then print the number of different birds.
Input:
Output:
If there are no sightings, print only Species: 0.
final scores = [72, 95, 88]; // List<int>
print(scores[0]); // 72 (indexes start at 0)
print(scores.length); // 3
scores.add(60); // [72, 95, 88, 60]
scores[1] = 99; // replace an item
print(scores.last); // 60final temps = [18, 23, 15, 27];
temps.sort(); // [15, 18, 23, 27], in place
print(temps.contains(23)); // true
print(temps.indexOf(27)); // 3
final warm = temps.where((t) => t > 20).toList(); // [23, 27]
final labels = temps.map((t) => '$t°').toList();
print(temps.join(', ')); // 15, 18, 23, 27final tags = {'dart', 'code'};
tags.add('dart');
print(tags.length); // 2final stock = {'apples': 12, 'pears': 4}; // Map<String, int>
stock['kiwis'] = 9; // add or replace
print(stock['apples']); // 12
print(stock['mangos']); // null: no such keyfinal pears = stock['pears'] ?? 0;final counts = <String, int>{};
for (final fruit in ['fig', 'kiwi', 'fig']) {
counts.update(fruit, (n) => n + 1, ifAbsent: () => 1);
}
print(counts); // {fig: 2, kiwi: 1}for (final MapEntry(:key, :value) in counts.entries) {
print('$key -> $value');
}40 95 72 95 18Count: 5
Best: 95
Ranking: 95, 95, 72, 40, 18robin
sparrow
robin
owl
robinrobin: 3
sparrow: 1
owl: 1
Species: 3