Thuta Learning
Dart
BasicProgrammingBeginner

Collections (Lists)

DartLesson 940 min

What you'll walk away with

  • Create a list, read, add and remove elements, and avoid a RangeError
  • Explain why growable, fixed-length and unmodifiable lists behave differently
  • Use map, where, fold and sort, knowing that map/where give a lazy Iterable and sort changes the original list
  • Build new lists with spread (...) and collection if/for

Explain it simply

Explain it simply

A list is a row of numbered boxes. The first box is number 0, the next is 1, and so on. Each box holds one value, and if you name the box number (the index) you get that value straight away. The order stays exactly as you put the values in.

Writing List<String> tells Dart that only Strings may go into the boxes. In this lesson you will see how the row can grow, when it is locked, how to copy it, and how to filter or transform its contents.

Problem → Why → Solution

The problem: a variable per value does not scale

Suppose you keep three lessons in three variables, lesson1, lesson2 and lesson3. Adding a fourth means writing a new variable and editing every place that prints them. If the number of lessons is only known when the program runs, for example when it comes from a file, you cannot even declare the variables in advance. And a loop cannot walk through them, because each has a separate name.

separate_variables.dart
void main() {
  String lesson1 = 'Syntax';
  String lesson2 = 'Variables';
  String lesson3 = 'Functions';

  // A fourth lesson needs a new variable and a new print line.
  print(lesson1);
  print(lesson2);
  print(lesson3);
}

What a list changes

A list gathers many values under one name. Its length can change at run time, so adding an item needs no code edits, and one for loop can walk through any number of them. That strength comes with rules you must know: an index past the end is an error, some lists cannot be changed, and map is lazy.

Core concept: how lists work and the rules to know

A list literal is written with [ ]. Dart infers List<String> from ['Syntax', 'Variables']. But var empty = []; has no elements to infer from and becomes List<dynamic>, so give an empty list its type: <String>[] or List<String> x = [];. Indexes start at 0, and length, first, last and isEmpty are available. An index outside the range, such as nums[5] on a three-element list, throws a RangeError whose message contains "Invalid value: Not in inclusive range 0..2: 5". Calling first on an empty list fails with "Bad state: No element".

To change a list you use add, addAll, insert, remove (by value), removeAt (by index), removeLast and clear; contains and indexOf search it. for (final item in list) is the normal way to visit each element. Adding to or removing from the same list inside that loop can raise a ConcurrentModificationError, so avoid it.

Lists come in three kinds. Ordinary literals ([1, 2]) and <int>[] are growable and can expand freely. List.filled(3, 0) is fixed-length: you can change elements, but add or remove throws "Unsupported operation: Cannot add to a fixed-length list". List.unmodifiable(source) and const [1, 2] are unmodifiable, so changing an element or adding one both throw an UnsupportedError. You can still add to a final list, because final only stops the variable from being reassigned.

var b = a; does not copy the list; it gives one list two names, so b.add(4) is visible through a. To copy, use [...a], List.of(a) or a.toList(). Those copies are shallow: lists nested inside are shared, not duplicated.

map, where, expand, take and skip return a lazy Iterable, not a List; printing one shows parentheses, as in (1, 4, 9), which tells them apart. Lazy means the function in between runs only while you iterate, and runs again on every iteration. Call .toList() when you need a real list. fold(initial, combine) reduces all elements into one value, and reduce throws on an empty list. sort() rearranges the list itself in place and returns void, so copy first if you need to keep the original order.

You can also build a list inside the literal itself. ...other spreads all its elements in place, and ...?maybeNull adds nothing when it is null. if (condition) item adds the element only when the condition holds, and for (var i in ...) item produces elements with a loop.

Mental model: numbered boxes
  1. Numbered boxes, starting at 0
  2. The element type limits what fits
  3. Growable, fixed or unmodifiable rules
  4. map and where stay lazy until toList

Methods such as add and sort change the original list, while map and where hand back a view rather than a new list.

General pattern

dart
List<Type> name = [item1, item2];
var empty = <Type>[];
name.add(item);                          // grow at the end
name[index];                             // RangeError if out of range
var copy = [...name];                    // independent, shallow copy
var picked = name.where((x) => test).toList();
name.sort((a, b) => a.compareTo(b));     // rearranges name itself

Declare the list with its type and put the elements in the literal; for an empty list state the type as <Type>[]. add and sort change the original list, while [...name] and where(...).toList() leave it untouched and produce something new.

Example: growing a lesson list and transforming it

This example creates a List<String> of lesson names and reads the first element. Then it adds one more with add and walks through the list with for-in. Finally it uses map and where to compute name lengths and to filter, and you should notice that both end with .toList().

lessons_list.dart
void main() {
  List<String> lessons = ['Syntax', 'Variables', 'Functions'];

  print('First lesson: ${lessons[0]}');

  lessons.add('Null Safety');

  for (final lesson in lessons) {
    print('Learn: $lesson');
  }

  // map and where are lazy: toList() builds the real list
  var lengths = lessons.map((l) => l.length).toList();
  print(lengths);

  var long = lessons.where((l) => l.length > 8).toList();
  print(long);

  print(lessons.length);
}

Code breakdown

  1. Line 2List<String> lessons = ['Syntax', 'Variables', 'Functions'];

    List<String> allows only Strings. A literal like this is a growable list, so you can add to it later.

  2. Line 4print('First lesson: ${lessons[0]}');

    Index 0 is the first element. Writing lessons[3] at this point would throw a RangeError, because only indexes 0 to 2 exist so far.

  3. Line 6lessons.add('Null Safety');

    add appends one element to the end and changes the list itself; the length becomes 4.

  4. Line 8for (final lesson in lessons) {

    for-in hands you each element in order without needing an index. final prevents reassigning lesson inside the loop.

  5. Line 13var lengths = lessons.map((l) => l.length).toList();

    map returns a lazy Iterable that turns each element into its length. Only .toList() produces the real list [6, 9, 9, 11].

  6. Line 16var long = lessons.where((l) => l.length > 8).toList();

    where keeps only elements for which the test is true, so 'Syntax' (6 letters) drops out. The lessons list itself is untouched.

You should see
First lesson: Syntax
Learn: Syntax
Learn: Variables
Learn: Functions
Learn: Null Safety
[6, 9, 9, 11]
[Variables, Functions, Null Safety]
4

Growable, fixed-length and unmodifiable

KindCreated withadd/remove and element change
Growable[1, 2], <int>[], List.of(x)Both allowed
Fixed-lengthList.filled(3, 0)add/remove throw; elements can change
UnmodifiableList.unmodifiable(x), const [1, 2]Both throw UnsupportedError

When a class has to hand its internal list to outsiders, List.unmodifiable protects it so other code cannot change it behind your back. The code below shows the behaviour of all three kinds and catches the UnsupportedError with try/catch. Notice at the end that add still works on a final list.

list_kinds.dart
void main() {
  var growable = [1, 2];
  growable.add(3);
  print(growable);

  var fixed = List.filled(3, 0);
  fixed[0] = 9;
  print(fixed);
  try {
    fixed.add(1);
  } on UnsupportedError catch (e) {
    print(e);
  }

  var locked = List.unmodifiable([1, 2]);
  try {
    locked[0] = 5;
  } on UnsupportedError catch (e) {
    print(e);
  }

  final names = ['Aye'];
  names.add('Ko');   // final stops reassignment, not changes to the list
  print(names);
}

Lazy transforms, sorting and building lists

In the code below, printing the result of where directly shows parentheses, and only .toList() gives the square-bracket list. prices.sort() changes prices itself, while [...prices]..sort(...) sorts only the copy, so the original prices stays as it was. The final perks list uses a collection if and a collection for inside the list literal.

transforms.dart
void main() {
  var prices = [1200, 450, 3000, 800];

  var cheap = prices.where((p) => p < 1000);
  print(cheap);                 // an Iterable, shown with parentheses
  print(cheap.toList());        // a real list

  final total = prices.fold(0, (sum, p) => sum + p);
  print(total);

  prices.sort();                // rearranges prices itself
  print(prices);

  var byLargest = [...prices]..sort((a, b) => b.compareTo(a));
  print(byLargest);
  print(prices);                // unchanged by the copy's sort

  bool vip = true;
  var perks = ['coffee', if (vip) 'lounge', for (var i = 1; i <= 2; i++) 'gift $i'];
  print(perks);
}

Do not pass fold straight into print

Writing print(prices.fold(0, (sum, p) => sum + p)) fails in Dart 3.13 with "The operator '+' isn't defined for the type 'Object?'." Because print's parameter is Object?, Dart infers fold's accumulator type as Object?. Store the result in a variable first (final total = ...) or spell the type out with fold<int>(0, ...).

In real projects

Where this shows up in real projects

In Flutter, ListView.builder(itemCount: items.length, itemBuilder: ...) looks at a list to decide how many rows to show. When a server sends a JSON array, jsonDecode gives back a List<dynamic>, so you convert it to a typed list with List<String>.from(raw) or .map(...).toList(). Shopping carts, todo lists and search results are all lists, and pagination uses take and skip.

State-handling code often prefers building a new list with [...items, newItem] and swapping it in rather than calling add in place, because it makes 'something changed' easy for the framework to notice. A class that exposes its internal list through a getter protects it with List.unmodifiable(_items). Tests often use const lists as expected values. All of these habits rest on the copy, unmodifiable and spread rules from this lesson.

Common mistakes

Common mistakes

1. Indexing past the end of the list

[1, 2, 3][5] throws a RangeError; Dart 3.13 prints "RangeError (length): Invalid value: Not in inclusive range 0..2: 5", and the word in parentheses may differ between SDK versions. Check length before indexing, and where the list might be empty use firstOrNull instead of first and handle the null.

2. Forgetting .toList()

Compiling List<int> sq = nums.map((n) => n * n); gives "A value of type 'Iterable<int>' can't be assigned to a variable of type 'List<int>'." map returns an Iterable, not a List, so add .toList() at the end. Left lazy, the function inside map can also run more than once.

3. Sharing one inner list through List.filled

Using List.filled(3, <int>[]) as a grid and calling grid[0].add(1) produces [[1], [1], [1]], because all three slots point at the same single list. List.generate(3, (_) => <int>[]) builds a new list each time and gives [[1], [], []].

4. Expecting sort() to return the sorted list

Writing var s = nums.sort(); and then using s gives "This expression has type 'void' and can't be used." sort rearranges nums itself and returns nothing; for a sorted copy write [...nums]..sort() or nums.toList()..sort().

Best practices

Best practices

  • Give every empty list a type such as <String>[]; otherwise it becomes List<dynamic>.
  • Use for (var i = 0; ...) only when you need the index, and prefer for-in everywhere else.
  • Do not add to or remove from a list inside a loop over that same list; collect first and remove afterwards, or use removeWhere.
  • Protect a list you hand out with List.unmodifiable, and use [...list] when you need a copy.

Mini challenge

Mini challenge: name and score helpers

Write three list helpers, none of which may change its input list, and then prove with print that the input is unchanged.

  • List<String> longNames(List<String> names, int minLength): return the names that are at least minLength long, as a list
  • List<int> topScores(List<int> scores, int count): return the count highest scores in descending order without changing the original
  • List<String> withBadge(List<String> names, bool vip): use spread and a collection if to append 'VIP' when vip is true
  • In main, call them with four names and five scores, and print the results and the original scores list
list_helpers.dart
List<String> longNames(List<String> names, int minLength) {
  // TODO: filter, then turn the lazy result into a real list
}

List<int> topScores(List<int> scores, int count) {
  // TODO: sort a COPY from highest to lowest, then take count items
}

List<String> withBadge(List<String> names, bool vip) {
  // TODO: build a new list with spread and a collection if
}

void main() {
  // TODO: create names and scores, call the helpers, print the results
  // TODO: print the original scores list to show it was not changed
}

Expected: Expected output: [Thida, Zaw Zaw] [95, 95, 88] [72, 95, 88, 61, 95] [Aye, VIP] [Aye]

Show hint

In topScores, do not sort the input directly; copy it with [...scores] first. The comparator (a, b) => b.compareTo(a) sorts from largest to smallest. take(count) returns an Iterable, so do not forget .toList().

Show solution
list_helpers.dart
List<String> longNames(List<String> names, int minLength) {
  return names.where((n) => n.length >= minLength).toList();
}

List<int> topScores(List<int> scores, int count) {
  final sorted = [...scores]..sort((a, b) => b.compareTo(a));
  return sorted.take(count).toList();
}

List<String> withBadge(List<String> names, bool vip) {
  return [...names, if (vip) 'VIP'];
}

void main() {
  final names = ['Aye', 'Thida', 'Min', 'Zaw Zaw'];
  final scores = [72, 95, 88, 61, 95];
  print(longNames(names, 5));
  print(topScores(scores, 3));
  print(scores);
  print(withBadge(['Aye'], true));
  print(withBadge(['Aye'], false));
}

Quick quiz 1 / 3

What does var a = [1, 2, 3]; var b = a; b.add(4); print(a.length); print?

Quick quiz 2 / 3

What does var nums = [1, 2, 3]; var r = nums.map((n) => n * 2); print(r); output?

Quick quiz 3 / 3

What happens when var fixed = List.filled(3, 0); fixed[1] = 5; fixed.add(7); runs?

What to remember

  • List indexes start at 0; going past the end is a RangeError, and first on an empty list gives "Bad state: No element".
  • Growable lists can change, List.filled has a fixed length, and List.unmodifiable and const [ ] cannot change at all.
  • var b = a shares one list; use [...a] to copy, remembering the copy is shallow.
  • map/where are lazy Iterables that need .toList(), and sort() changes the list itself and returns void.

Dart language overview — Dart

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Collections (Lists) | Thuta Learning