Dart Lists
A list is a container that holds many values in order. The values in a list keep the order they were written in.
A list printed whole
scores holds three numbers in a list. print shows the whole list with its brackets.
void main() {
var scores = [10, 20, 30];
print(scores);
}One value by index
Index 0 names the first value in the list. print shows that first value alone.
void main() {
var scores = [10, 20, 30];
print(scores[0]);
}The length of a list
length counts the values stored in scores. print shows the count 3.
void main() {
var scores = [10, 20, 30];
print(scores.length);
}Each value with for-in
The for-in loop visits each name in the stored list. Each visit prints one name on its own line.
void main() {
var names = ['Ana', 'Bo', 'Cy'];
for (var name in names) {
print(name);
}
}Example
void main() {
var colors = ['red', 'blue', 'green'];
print(colors);
print(colors.length);
print(colors[1]);
for (var color in colors) {
print(color);
}
}Key points
- Use square brackets to write a list of values.
- A value in a list is reached by its index in square brackets.
- The first value in a list sits at index 0.
- Use length to count the values in a list.
- Use a for-in loop to visit each value in a stored list in order.
In this example, colors holds three text values in a list. The first print shows the whole list. The next print shows the length 3. The next print shows the value at index 1, which is blue. The for-in loop then prints red, blue, and green on separate lines.
Note
An empty list is written with empty square brackets.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
At which index does the first value in a list sit?