Async and Practical
Word Count with Map
Counting words is a classic map exercise: split the text, walk each word, and increment its tally in a map. Default Dart maps keep insertion order, so the summary stays stable.
Program
Play the program to tally six words and build a deterministic summary string.
word_count.dart
void main() {
var text = 'red blue red green blue red';
var words = text.split(' ');
var counts = <String, int>{};
for (var w in words) {
counts[w] = (counts[w] ?? 0) + 1;
}
var entries = counts.entries;
var parts = entries.map((e) => '${e.key}:${e.value}');
var summary = parts.join(',');
print(summary);
}
split
`'red blue ... red'.split(' ')` returns `[red, blue, red, green, blue, red]`.
counter map
`?? 0` starts unseen words at zero before the program adds one.
insertion order
Walking `counts.entries` keeps insertion order, so the joined summary is deterministic.