What is a List?
A List is an ordered collection of items. Lists allow duplicate values and maintain insertion order. They are the most commonly used collection type in Dart.
Creating Lists
// Fixed-type list
List<int> numbers = [1, 2, 3, 4, 5];
List<String> names = ['Alice', 'Bob', 'Carol'];
// Type inference
var fruits = ['apple', 'banana', 'cherry'];
// Empty list
List<double> scores = [];
// Fixed-length list (cannot add/remove)
var fixed = List<int>.filled(5, 0); // [0, 0, 0, 0, 0]
// Generated list
var squares = List<int>.generate(5, (i) => (i + 1) * (i + 1));
// [1, 4, 9, 16, 25]
Accessing Elements
var fruits = ['apple', 'banana', 'cherry'];
print(fruits[0]); // apple (first)
print(fruits.last); // cherry (last)
print(fruits.length); // 3
print(fruits.isEmpty); // false
print(fruits.isNotEmpty); // true
Common Methods
| Method | Description |
add(item) | Add one item to the end |
addAll(list) | Add all items from another list |
insert(i, item) | Insert at index i |
remove(item) | Remove first occurrence |
removeAt(i) | Remove item at index i |
contains(item) | Check if item exists |
indexOf(item) | Find index of item |
sort() | Sort in place |
reversed | Iterable in reverse order |
sublist(start, end) | Extract sub-list |
Example
void main() {
List<String> tasks = ['Write code', 'Test code', 'Deploy'];
tasks.add('Monitor');
tasks.insert(0, 'Plan');
print(tasks); // [Plan, Write code, Test code, Deploy, Monitor]
tasks.remove('Test code');
print(tasks.length); // 4
print(tasks.contains('Deploy')); // true
print(tasks.indexOf('Deploy')); // 2
var numbers = [3, 1, 4, 1, 5, 9, 2, 6];
numbers.sort();
print(numbers); // [1, 1, 2, 3, 4, 5, 6, 9]
print(numbers.sublist(2, 5)); // [2, 3, 4]
}
Output:[Plan, Write code, Test code, Deploy, Monitor]
4
true
2
[1, 1, 2, 3, 4, 5, 6, 9]
[2, 3, 4]
💪 Exercise
- Create a list of 5 favourite movies, add two more, then print only the first 3.
- Sort a list of numbers in descending order.
- Find the maximum value in a list without using any built-in max method.
🧠 Quiz
1. How do you access the last element of a Dart list?
- A) list[-1]
- B) list.last ✅
- C) list.end()
- D) list[list.length]
2. Which method removes an element by value (not index)?
- A) removeAt()
- B) delete()
- C) remove() ✅
- D) pop()
Summary
Dart Lists are ordered, indexed, and allow duplicates. Create them with literal syntax [...] or List.generate(). Key methods: add(), remove(), sort(), contains(), sublist(). Access elements by index (zero-based) or with .first/.last.