Follow these steps to understand and use Dart collections:
- Create the playground function that will call the examples for each collection type we're going to cover:
void collectionPlayground() {
listPlayground();
mapPlayground();
setPlayground();
collectionControlFlow();
}
- First up is Lists, more commonly known as arrays in other languages. This function shows how to declare, add, and remove data from a list:
void listPlayground() {
// Creating with list literal syntax
final List<int> numbers = [1, 2, 3, 5, 7];
numbers.add(10);
numbers.addAll([4, 1, 35]);
// Assigning via subscript
numbers[1] = 15;
print('The second number is ${numbers[1]}');
// enumerating a list
for (int number in numbers) {
print(number);
}
}
- Maps store two points of data per element – a key and a value. Keys are used to write and retrieve the values stored in the list. Add this function to see Map in action:
void mapPlayground() {
// Map Literal syntax
final MapString, int ages = {
'Mike': 18,
'Peter': 35,
'Jennifer': 26,
};
// Subscript syntax uses the key type.
// A String in this case
ages['Tom'] = 48;
final ageOfPeter = ages['Peter'];
print('Peter is $ageOfPeter years old.');
ages.remove('Peter');
ages.forEach((String name, int age) {
print('$name is $age years old');
});
}
- Sets are the least common collection type, but still very useful. They are used to store values where the order is not important, but all the values in the collection must be unique. The following function shows how to use sets:
void setPlayground() {
// Set literal, similar to Map, but no keys
final final Set<String> ministers = {'Justin', 'Stephen', 'Paul', 'Jean', 'Kim', 'Brian'};
ministers.addAll({'John', 'Pierre', 'Joe', 'Pierre'}); //Pierre is a duplicate, which is not allowed in a set.
final isJustinAMinister = ministers.contains('Justin');
print(isJustinAMinister);
// 'Pierre' will only be printed once
// Duplicates are automatically rejected
for (String primeMinister in ministers) {
print('$primeMinister is a Prime Minister.');
}
}
- Another Dart feature is the ability to include control flow statements directly in your collection. This feature is also one of the few examples where Flutter directly influences the direction of the language. You can include if statements, for loops, and spread operators directly inside your collection declarations. We will be using this style of syntax extensively when we get to Flutter in the next chapter. Add this function to get a feel for how control flows work on more simplistic data:
void collectionControlFlow() {
final addMore = false;
final randomNumbers = [
34,
232,
54,
32,
if (addMore) ...[
534343,
4423,
3432432,
],
];
final duplicated = [
for (int number in randomNumbers) number * 2,
];
print(duplicated);
}