Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 61 ยท Collections

Lists

Learn Dart lists: growable and fixed-length lists, adding and removing items, sublists, sorting, the spread operator, collection if and collection for, with examples.

A list is an ordered collection of values that you reach by position. It is the collection you will use most in Dart: a list of names, a list of prices, a list of widgets in a Flutter screen. Dart's List<E> is a class with a rich set of methods, and it has some special syntax that makes building lists pleasant: list literals, the spread operator and if/for inside the brackets.

The Dart code in this lesson is read-only. TypeScript stand-ins let you run the same ideas, and the text points out where JavaScript arrays behave differently.

Creating lists

The simplest way is a list literal. Dart infers the element type from the contents:

DART
void main() {
  var primes = [2, 3, 5, 7];          // List<int>
  var mixed = [1, 'two', 3.0];        // List<Object>
  var names = <String>[];             // empty list, element type spelled out
  List<double> prices = [];           // empty list, type from the variable

  print(primes);        // [2, 3, 5, 7]
  print(mixed);         // [1, two, 3.0]
  print(names.length);  // 0
}

An empty literal like [] needs a type from somewhere, either the variable's declared type or an explicit <String>[]. Without one, Dart infers List<dynamic>, which throws away type safety. Prefer an explicit type for empty lists.

There are also constructors for lists that follow a pattern:

DART
void main() {
  var zeros = List.filled(3, 0);                    // [0, 0, 0] (fixed length!)
  var squares = List.generate(5, (i) => i * i);     // [0, 1, 4, 9, 16]
  var copy = List.of(squares);                      // a new list with the same items
  var fromSet = {3, 1, 2}.toList();                 // from any iterable
  print(zeros);
  print(squares);
  print(copy);
  print(fromSet);
}

Read the comment on List.filled: by default it makes a fixed-length list. Pass growable: true if you need to add to it. List.generate creates a growable list by default.

Growable, fixed-length and unmodifiable

Not every list can change. There are three flavours, and mixing them up is a common source of runtime errors.

Kind How you get it Can change length? Can change items?
Growable a list literal, List.generate, toList() yes yes
Fixed-length List.filled(3, 0) no yes
Unmodifiable const [1, 2], List.unmodifiable(x) no no

Calling add on a fixed-length or unmodifiable list throws an UnsupportedError. Assigning to an item of an unmodifiable list throws too.

DART
void main() {
  var fixed = List.filled(2, 'x');
  fixed[0] = 'y';          // fine: changing an item
  // fixed.add('z');       // UnsupportedError: cannot add to a fixed-length list

  const frozen = [1, 2, 3];
  // frozen[0] = 9;        // UnsupportedError: cannot modify an unmodifiable list
  print(fixed);
  print(frozen);
}
flowchart TD
    A["List of E"] --> B["Growable<br/>[1, 2, 3]"]
    A --> C["Fixed-length<br/>List.filled(3, 0)"]
    A --> D["Unmodifiable<br/>const [1, 2, 3]"]
    B -->|"add, remove, set items"| E["everything works"]
    C -->|"set items only"| F["add throws UnsupportedError"]
    D -->|"read only"| G["any change throws"]

Three flavours of list: the type is the same, but what you may do differs.

Reading and searching

Indexes start at zero. Reading outside the list throws a RangeError, so check the length first when the index comes from outside:

DART
void main() {
  var fruits = ['apple', 'banana', 'cherry'];
  print(fruits[0]);              // apple
  print(fruits.first);           // apple
  print(fruits.last);            // cherry
  print(fruits.length);          // 3
  print(fruits.isEmpty);         // false
  print(fruits.contains('fig')); // false
  print(fruits.indexOf('cherry')); // 2
  print(fruits.indexOf('fig'));    // -1 (not found)
  // print(fruits[3]);           // RangeError (index): Invalid value
}

first and last on an empty list also throw (a StateError). Use firstOrNull or lastOrNull (from dart:core since Dart 3.0) when the list might be empty.

Adding and removing

DART
void main() {
  var list = [10, 20, 30];

  list.add(40);                 // [10, 20, 30, 40]
  list.addAll([50, 60]);        // [10, 20, 30, 40, 50, 60]
  list.insert(0, 5);            // [5, 10, 20, 30, 40, 50, 60]
  list.insertAll(1, [6, 7]);    // [5, 6, 7, 10, 20, 30, 40, 50, 60]

  var removed = list.remove(7);       // true: removes the first matching value
  var gone = list.removeAt(0);        // returns the removed item: 5
  var last = list.removeLast();       // returns 60
  list.removeWhere((n) => n > 40);    // removes 50
  print(list);                        // [6, 10, 20, 30, 40]
  print([removed, gone, last]);       // [true, 5, 60]

  list.clear();
  print(list.isEmpty);                // true
}

remove(value) returns a bool telling you whether something was removed; removeAt(index) returns the item that was removed. Methods that change the list in place, like these, return void or a small result, never the list itself.

TypeScript Changing a list (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Sublists and ranges

sublist(start, end) copies a slice into a new list; the end index is exclusive and may be left out. getRange gives a lazy view instead:

DART
void main() {
  var letters = ['a', 'b', 'c', 'd', 'e'];
  print(letters.sublist(1, 3));      // [b, c]
  print(letters.sublist(3));         // [d, e]
  print(letters.take(2).toList());   // [a, b]
  print(letters.skip(3).toList());   // [d, e]
  print(letters.reversed.toList());  // [e, d, c, b, a]
}

Note that reversed, take and skip return an iterable, not a list, so you add .toList() when you need a list. The next lessons explain why.

Sorting

sort() changes the list in place. With no argument it uses the items' natural order, so the items must be Comparable (numbers and strings are). Pass a comparison function otherwise: it returns a negative number if the first argument comes first, zero if they tie, and a positive number if it comes second.

DART
void main() {
  var nums = [5, 3, 9, 1];
  nums.sort();
  print(nums);                          // [1, 3, 5, 9]

  var words = ['pear', 'fig', 'banana'];
  words.sort((a, b) => a.length.compareTo(b.length));
  print(words);                         // [fig, pear, banana]

  nums.sort((a, b) => b.compareTo(a));  // descending
  print(nums);                          // [9, 5, 3, 1]

  var sortedCopy = [...words]..sort();  // sort a copy, keep the original
  print(sortedCopy);                    // [banana, fig, pear]
}

sort returns void, so var sorted = list.sort(); is a classic mistake. If you need to keep the original order, copy first. The sort is not guaranteed to be stable, so do not rely on equal items keeping their relative order.

Spread, collection if and collection for

Dart lets you build a list from other lists and conditions right inside the literal. The spread operator ... inserts all items of another collection; ...? does the same but accepts null and inserts nothing:

DART
void main() {
  var base = [1, 2];
  List<int>? extra;                    // null
  var all = [0, ...base, ...?extra, 3];
  print(all);                          // [0, 1, 2, 3]
}

Collection if includes an element only when a condition holds, and collection for generates elements from a loop:

DART
void main() {
  var isAdmin = true;
  var menu = [
    'Home',
    'Profile',
    if (isAdmin) 'Settings',
    for (var i = 1; i <= 2; i++) 'Item $i',
  ];
  print(menu);   // [Home, Profile, Settings, Item 1, Item 2]
}

This style replaces a lot of "create an empty list, then add in a loop" code. It is also the normal way to build the children of a Flutter widget.

TypeScript Building lists declaratively (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Lists hold references

A list of objects holds references, not copies. Copying a list with List.of or the spread operator is shallow: the new list has the same objects inside. Changing a mutable object through one list is visible through the other:

DART
void main() {
  var a = [StringBuffer('x')];
  var b = [...a];
  b.first.write('y');
  print(a.first);   // xy: both lists share the same StringBuffer
}

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does List.filled(3, 0) create by default?

    List.filled makes a fixed-length list unless you pass growable: true. You can change its items but calling add throws an UnsupportedError.
  2. 2. What does var s = [3, 1, 2].sort(); store in s?

    sort changes the list in place and returns void, so the variable cannot hold the sorted list. Sort first, then use the list, or sort a copy.
  3. 3. Which line builds [1, 2, 3, 4] when bool more = true?

    Collection if includes an element only when its condition is true. The ternary needs an else branch, plain + does not add an item, and spread needs a collection, not a number.
  4. 4. Why is List.of(a) called a shallow copy?

    The new list is separate, but both lists hold references to the same objects, so mutating one of those objects is visible through both lists.

Summary

  • A list literal like [1, 2, 3] is growable; List.filled is fixed-length by default; const lists are unmodifiable.
  • Reading out of range throws RangeError; add on a fixed-length list throws UnsupportedError.
  • add, addAll, insert, remove, removeAt, removeLast and removeWhere change a list in place.
  • sort works in place and returns void; copy first to keep the original.
  • Spread (..., ...?), collection if and collection for build lists declaratively.
  • Copies are shallow: the objects inside are shared.

Next, learn about collections without duplicates in Sets.