Dart List

Summary: in this tutorial, you’ll how to use the Dart List class to manage an ordered collection of elements effectively.

Introduction to the Dart List type

A list is an indexable collection of objects with a length. A list may contain duplicate elements and null. Dart uses the List<E> class to manage lists.

Creating a list

The following creates an empty list that will store integers:

int scores = [];Code language: Dart (dart)

To create a list and initializes its elements, you place a comma-separated list of elements inside the square brackets ([]). In this example, Dart infers the list as List<int>.

For example, the following creates a list of integers that have 4 numbers:

int scores = [1, 3, 4, 2];Code language: Dart (dart)

You can reassign the scores with an empty list:

scores = [];Code language: Dart (dart)

Dart understands that the scores is a list of integers. If you attempt to assign a list of strings to it, you’ll get an error:

scores = ['one', 'three', 'four', 'two'];Code language: Dart (dart)

Error:

A value of type 'List<String>' can't be assigned to a variable of type 'int'.Code language: Dart (dart)

Since the elements in the list are integers, you can use the var keyword to declare the list:

var scores = [1, 3, 4, 2];Code language: Dart (dart)

However, if you use the var keyword to declare a list and initialize its value to an empty list, Dart will infer the type of its elements as dynamic i.e., List<dynamic>. For example:

var scores = [];Code language: Dart (dart)

If you do this, you’ll lose type safety.

Displaying a list

To show the elements of a list, you can use the print() function. For example:

void main() {
  var scores = [1, 3, 4, 2];
  print(scores);
}Code language: Dart (dart)

Output:

[1, 3, 4, 2]Code language: Dart (dart)

Accessing elements

Lists are zero-based indexing. It means that the first element has an index of 0, the second element has an index of 1, and so on.

To access an element, you use subscript notation where the index goes within square brackets after the list name:

listName[index]Code language: Dart (dart)

For example, the following displays the 3rd element of the scores list:

void main() {
  var scores = [1, 3, 4, 2];
  print(scores[2]);
}Code language: Dart (dart)

Assign values to elements

To assign a value to an element, you also use the subscript notation. For example:

void main() {
  var scores = [1, 3, 4, 2];
  scores[2] = 5;

  print(scores);
}Code language: Dart (dart)

Output:

[1, 3, 5, 2]Code language: Dart (dart)

In this example, we assign 5 to the 3rd element of the scores list.

Adding elements to a list

To add an element to a list, you use the add() method. The add() method appends an element at the end of a list. For example:

void main() {
  var scores = [1, 3, 4, 2];
  scores.add(5);
  print(scores);
}Code language: Dart (dart)

Output:

[1, 3, 4, 2, 5]Code language: Dart (dart)

Removing elements from a list

To remove an element from a list, you use the remove() method. The following example uses the remove() method to remove number 1 from the scores list:

void main() {
  var scores = [1, 3, 4, 2];
  scores.remove(1);
  print(scores);
}Code language: Dart (dart)

Output:

[3, 4, 2]Code language: Dart (dart)

Immutable list

To prevent a list from being reassigned to another list, you use the final keyword. For example:

final scores = [1, 3, 4, 2, 5];Code language: Dart (dart)

Since the scores list is final, you won’t be able to reassign it to another list. For example, the following will result in an error:

scores = [];Code language: Dart (dart)

Error:

The final variable 'scores' can only be set once.Code language: Dart (dart)

However, you can operate on the list by adding an element or removing an existing element. For example:

void main() {
  final scores = [1, 3, 4, 2, 5];
  scores.add(6);
  print(scores);
}Code language: Dart (dart)

Output:

[1, 3, 4, 2, 5, 6]Code language: Dart (dart)

To make a list truly immutable, you use the const instead of the final keyword:

void main() {
  const scores = [1, 3, 4, 2, 5];
  scores.add(6); // error
}Code language: Dart (dart)

Output:

Unsupported operation: Cannot add to an unmodifiable listCode language: Dart (dart)

List properties

To get the number of elements of a list, you use the length property. For example:

void main() {
  var scores = [1, 3, 4, 2, 5];
  print('Length: ${scores.length}');
}Code language: Dart (dart)

To access the first and last elements of a list, you use the first and last properties. For example:

void main() {
  var scores = [1, 3, 4, 2, 5];
  //
  print('First: ${scores.first}');
  print('Last: ${scores.last}');
}Code language: Dart (dart)

Output:

First: 1
Last: 5Code language: Dart (dart)

To check if a list contains any elements, you can use the isEmpty or isNotEmpty property. For example:

void main() {
  var scores = [];
  print(scores.isEmpty); // true
  print(scores.isNotEmpty); // false
}Code language: Dart (dart)

Iterating over list elements

To iterate over list elements, you can use the for statement:

void main() {
  var scores = [1, 3, 4, 2, 5];
  for (var i = 0; i < scores.length; i++) {
    print(scores[i]);
  }
}Code language: Dart (dart)

Output:

1
3
4
2
5Code language: Dart (dart)

In this example, we use a for loop that starts from the element 0 and ends at the element length-1. In each iteration, we access the element at an index and print it out.

The for loop is quite verbose because you have to maintain a current index of the list elements. To make the code more concise, you can use the for in loop:

void main() {
  var scores = [1, 3, 4, 2, 5];
  for (var score in scores) {
    print(score);
  }
}Code language: Dart (dart)

In this example, the for-in loop assigns an element from the scores list to the score variable in each iteration.

The List also has the forEach() method that executes a function for each element. For example:

void main() {
  var scores = [1, 3, 4, 2, 5];
  scores.forEach((score) => print(score));
}Code language: Dart (dart)

The function that you pass into the forEach() method takes the current element of the list as an argument. In this example, we pass an arrow function to the forEach() method, which prints out the score.

Because the print() function is the same as the input forEach() method, you can make it shorter like this:

void main() {
  var scores = [1, 3, 4, 2, 5];
  scores.forEach(print);
}Code language: Dart (dart)

Spreading list elements

The spread operator (...) spreads list elements. For example, you can use the spread operator to combine multiple lists into one like this:

void main() {
  var lower = [1, 2, 3];
  var upper = [4, 5];
  var scores = [...lower, ...upper];
  print(scores);
}Code language: Dart (dart)

In this example, the ...lower returns all elements of the lower list and the ...upper returns all elements of the upper list. Therefore, the scores list contains all elements of both the lower and upper lists.

Collection if

Dart provides you with a collection if for creating a list. The collection if to determine whether an element is included in a list based on a condition. For example:

void main() {
  var bye = true;
  var greetings = [
    if (bye) 'Good Bye',
    'Hi',
    'Hi there',
  ];

  print(greetings);
}Code language: Dart (dart)

In this example, if the bye variable is true, the collection if will include the 'Good Bye' element in the greetings list. Note that you can place an if collection anywhere in the list. It doesn’t have to be at the beginning of the list.

Collection for

When creating a list, you can also use a collection for to generate elements from another list. For example:

void main() {
  var numbers = [1, 2, 3];
  var scores = [0, for (var number in numbers) number * 2];
  print(scores);
}Code language: Dart (dart)

Output:

[0, 2, 4, 6]Code language: Dart (dart)

In this example, we use a for collection to iterate over the elements of the numbers list, double each of them, and assign the results as elements for the scores list.

Summary

  • Use List<E> class to manage an indexable collection of elements. Lists are zero-based indexing.
  • Use the add() method to append an element to a list.
  • Use the remove() method to remove an element from a list.
  • Use for, for-in, and forEach() to iterate over list elements.
  • Use the final keyword to define a list that can be assigned once.
  • Use the const keyword to define an immutable list.
Was this tutorial helpful ?