Lists in Dart
In this lesson, you will learn about Lists in Dart. Lists are one of the most commonly used data structures and are used to store multiple values in a single variable.
In real-world applications, lists are used to store things like user names, product prices, scores, messages, orders, and much more.
What Is a List?
A list is an ordered collection of elements.
Each element in a list has a position (index), starting from 0.
All elements in a Dart list usually belong to the same data type.
Creating a List
Let’s create a list of product prices in an online store.
List prices = [1200, 850, 430, 999];
print(prices);
This list stores the prices of four products.
Accessing List Elements
Each element in a list can be accessed using its index.
Remember, indexing starts from 0.
print(prices[0]); // First price
print(prices[2]); // Third price
This allows you to retrieve specific data from a list.
Real Example: Student Scores
Consider a list storing test scores of students.
List scores = [78, 85, 90, 66, 88];
print("First score: ${scores[0]}");
print("Last score: ${scores[scores.length - 1]}");
This pattern is commonly used in education and analytics applications.
Adding Elements to a List
You can add new elements using the add() method.
scores.add(92);
print(scores);
This is useful when data is added dynamically, such as new user entries.
Removing Elements from a List
You can remove elements using remove() or removeAt().
scores.remove(66); // Removes value
scores.removeAt(0); // Removes first element
print(scores);
This is common in scenarios like deleting items from a cart.
Looping Through a List
Lists are often processed using loops.
for (int score in scores) {
print("Score: $score");
}
This allows you to work with each element one by one.
Updating List Elements
You can update an element by assigning a new value to its index.
scores[1] = 95;
print(scores);
This is useful when correcting or modifying stored data.
Checking List Length
The length property returns the number of elements in a list.
print("Total scores: ${scores.length}");
This is helpful for validations and loops.
Types of Lists
Dart supports different types of lists:
- Fixed-length lists – Size cannot change
- Growable lists – Size can change (most common)
Real-World Use Cases
- List of registered users
- Product catalog
- Messages in a chat app
- Scores and analytics data
📝 Practice Exercises
Exercise 1
Create a list of five city names and print them.
Exercise 2
Add a new element to a numeric list and display the updated list.
Exercise 3
Loop through a list and print each element.
✅ Practice Answers
Answer 1
List cities = ["New York", "London", "Tokyo", "Paris", "Sydney"];
print(cities);
Answer 2
List numbers = [1, 2, 3];
numbers.add(4);
print(numbers);
Answer 3
for (var city in cities) {
print(city);
}
What’s Next?
In the next lesson, you will learn about Sets in Dart.
Sets help you store unique values and are useful when duplicates are not allowed.