Understanding Lists and Maps with programming and real-world examples.
A List in Dart is an ordered collection of items, where each item has an index starting from 0. Lists allow you to store multiple values in one variable and access them by their position.
Think of a grocery shopping list. You write down the items you want to buy in order: Apples, Bread, Milk, Eggs. You can look at the 1st item, 2nd item, and so on.
void main() {
List groceries = ['Apples', 'Bread', 'Milk', 'Eggs'];
print(groceries[0]); // Output: Apples
print(groceries.length); // Output: 4
groceries.add('Cheese'); // Add new item
print(groceries); // Output: [Apples, Bread, Milk, Eggs, Cheese]
}
Here, groceries is a list holding multiple strings. You can access items by index and add new items.
A Map in Dart is a collection of key-value pairs. Each value is associated with a unique key, and you use the key to retrieve the value. Think of it like a dictionary.
Imagine a phonebook, where each person's name is the key and their phone number is the value. You look up a person's name (key) to get their number (value).
void main() {
Map phoneBook = {
'Alice': '123-456-7890',
'Bob': '987-654-3210',
'Charlie': '555-555-5555'
};
print(phoneBook['Bob']); // Output: 987-654-3210
phoneBook['David'] = '111-222-3333'; // Add new entry
print(phoneBook);
// Output: {Alice: 123-456-7890, Bob: 987-654-3210, Charlie: 555-555-5555, David: 111-222-3333}
}
In this example, phoneBook maps names (keys) to phone numbers (values).