Working with collections in dart involves manipulating lists, maps, and sets efficiently. Dart provides built-in classes and methods to work with these data structures effectively. Here's a brief overview:
List
numbers.add(6); // Adds 6 to the end of the list
numbers.insert(0, 0); // Inserts 0 at index 0
int firstElement = numbers[0];
numbers.removeAt(2); // Removes the element at index 2
for (var number in numbers) {
print(number);
}
Map < String, int> ages = {
'Alice': 30,
'Bob': 25,
'Charlie': 35,
};
Adding elements:
ages['David'] = 40; // Adds a new key-value pair
int aliceAge = ages['Alice'];
ages.remove('Bob');
Iterating through a map:
ages.forEach((name, age) {
print('$name is $age years old');
});
Set< int > numbers = {1, 2, 3, 4, 5};
numbers.add(6);
numbers.remove(4);
for (var number in numbers) {
print(number);
}