Lesson 9 · 9 of 20
Lists · Dart
Store several values in order with Dart lists: List<String>, indexes from 0, first and last, looping with for-in, contains and indexOf.

A list keeps several values in order, between square brackets: ['Mercury', 'Venus', 'Earth', 'Mars']. The type `List<String>` says it is a list of strings; whatever goes between < > is the type of its elements. print(planets) prints all of it and length says how many elements it has.
Each element has a position (index) starting at 0: planets[0] is Mercury and the last one is at length - 1. Since asking for the first and last is so common, lists have `first` and `last`.
planets[3] = 'Mars (the red one)' changes the element at that position. And the `for-in` loop goes through the list one element at a time: for (var planet in planets) puts each planet in planet, with no indexes to worry about.
With var, Dart infers the type: [0, 0, 1, 2] is a List<int>. The classic for with an index works too, here to add up the moons.
Lists answer questions: `contains()` tells whether a value is there, `indexOf()` gives its position (or -1 if it is missing, as with Pluto) and `isEmpty` tells whether the list is empty.
Code · main.dart
void main() { // A list keeps values in order, between [ ]. List<String> planets = ['Mercury', 'Venus', 'Earth', 'Mars']; print(planets); print('The list has ${planets.length} planets'); // Positions start at 0, so the last one is length - 1. print('First: ${planets[0]}, last: ${planets[planets.length - 1]}'); print('Also: ${planets.first} and ${planets.last}'); // A position can be given a new value. planets[3] = 'Mars (the red one)'; // for-in goes through every element. for (var planet in planets) { print('- $planet'); } // var works out the type: here, List<int>. var moons = [0, 0, 1, 2]; int total = 0; for (int i = 0; i < moons.length; i++) { total += moons[i]; } print('Moons in total: $total'); // contains, indexOf and isEmpty answer questions. print('Has Venus? ${planets.contains('Venus')}'); print('Earth is at position ${planets.indexOf('Earth')}'); print('Pluto is at ${planets.indexOf('Pluto')}. Empty? ${planets.isEmpty}');}Output · dart run main.dart
[Mercury, Venus, Earth, Mars] The list has 4 planets First: Mercury, last: Mars Also: Mercury and Mars - Mercury - Venus - Earth - Mars (the red one) Moons in total: 3 Has Venus? true Earth is at position 2 Pluto is at -1. Empty? false
Key points
- A list goes between
[ ]; its type isList<T>. - The first element is at
[0]; the last at[length - 1]. firstandlastgive the ends.for (var x in list)goes through the elements.indexOfgives-1when the value is missing.
Exercise
Create a list with a week's temperatures, loop through it with for-in to work out the average, and also print the first and last day's temperature.