Skip to content
AgileLogics
6 min read

Lists

Prerequisites: Loops: for and for-in

A list is an ordered collection of values — Dart's version of an array.

Real-world analogy: a list is a numbered row of lockers. Each locker holds one item, and you find an item by its locker number.

Creating lists

final fruits = ['apple', 'banana', 'cherry'];   // List<String>
final scores = <int>[];                         // empty List<int>

Reading elements

Positions (indexes) start at 0:

void main() {
  final fruits = ['apple', 'banana', 'cherry'];

  print(fruits[0]);
  print(fruits[2]);
  print(fruits.length);
  print(fruits.first);
  print(fruits.last);
  print(fruits.indexOf('banana'));
  print(fruits.contains('cherry'));
  print(fruits.isEmpty);
}
apple
cherry
3
apple
cherry
1
true
false

Changing a list

void main() {
  final fruits = ['apple', 'banana'];

  fruits.add('cherry');
  fruits.insert(0, 'apricot');
  fruits[1] = 'avocado';
  print(fruits);

  fruits.remove('banana');
  fruits.removeAt(0);
  print(fruits);

  fruits.addAll(['date', 'fig']);
  print(fruits);
}
[apricot, avocado, banana, cherry]
[avocado, cherry]
[avocado, cherry, date, fig]

Note that fruits is final — the variable always refers to the same list — yet the list's contents can change. final stops reassignment, not modification. A const list, on the other hand, can't be changed at all.

Collection if, for, and spread

Dart can build lists with logic right inside the brackets:

void main() {
  const isMember = true;
  final base = [1, 2];

  final items = [
    ...base,
    3,
    if (isMember) 99,
    for (final n in base) n * 10,
  ];
  print(items);
}
[1, 2, 3, 99, 10, 20]
  • ...base spreads another list's elements in.
  • if and for inside a list literal add elements conditionally or in a loop — used constantly in Flutter to build lists of widgets.

Common mistakes

  • Reading past the end: fruits[3] on a 3-element list throws a RangeError.
  • Calling first on an empty list throws; use firstOrNull when the list might be empty.

Practice

Create a list of three cities, add a fourth, and print the list, its length, and the last city.

Show solution
void main() {
  final cities = ['Lagos', 'Lima', 'Oslo'];
  cities.add('Tokyo');
  print(cities);
  print(cities.length);
  print(cities.last);
}
[Lagos, Lima, Oslo, Tokyo]
4
Tokyo