CodeBlanks Logo Icon CodeBlanks

List

Learn dynamic arrays with List<T>.

List<T>

List<T> is the most common collection in Dart. It holds ordered elements; the same value can appear more than once. T sets the element type; for example List<int> holds only integers.

Two ways to create a list: var a = [1, 2, 3]; or var b = <String>['A', 'B'];. The second states the type explicitly. The add method appends elements and the length property gives the count.

Lists are accessed by index: a[0] returns the first element. Indexing starts at zero. This lesson teaches how to create, fill and print lists.

List operations

To append an element use list.add(value). The list length comes from list.length. Printing the whole list with print(list) shows it as [a, b, c].

Example: var fruits = <String>['Apple', 'Banana']; fruits.add('Cherry'); print(fruits);. Output: [Apple, Banana, Cherry]. fruits.length gives 3.

Index access works too: fruits[0] returns 'Apple'. Indexing starts at zero and goes up to length - 1.

Practice Create a fruit list

Create a fruit list with <String>['Apple', 'Banana', 'Cherry']. Add 'Date' with add. Print the list first, then the length.

Starter code

main.dart
void main() {
  // create a String list of fruits, add an element with add
  // print the list and its length
}

Sample solution

main.dart
void main() {
  var fruits = <String>['Apple', 'Banana', 'Cherry'];
  fruits.add('Date');
  print(fruits);
  print(fruits.length);
}

Expected output

[Apple, Banana, Cherry, Date]
4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which property does List<T> have?

  • Ordered and allows duplicates Correct answer
  • Holds only unique elements
  • Stores key-value pairs
  • Works in FIFO order

Explanation: List is ordered and can hold the same value more than once.

2 Add an element to the list

Question
var fruits = <String>['Apple', 'Banana'];
fruits.____('Cherry');
Answer
var fruits = <String>['Apple', 'Banana'];
fruits.add('Cherry');

Explanation: the add method appends an element to the list.

3 Match the list methods

Term Meaning
add(x) Add element
length Element count
[0] First element
[length - 1] Last element

All lessons in Intermediate