๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Dart List Methods

A list method is a named action that a list can perform. Some methods change the list and some methods report a fact about it.

Adding and removing values

add puts 3 at the end of the list and remove takes 2 out. The two print lines show the list after each change.

void main() {
  var scores = [1, 2];
  scores.add(3);
  print(scores);
  scores.remove(2);
  print(scores);
}

Asking about a value

contains answers whether Bo sits in the list. indexOf gives the index of Bo.

void main() {
  var names = ['Ana', 'Bo', 'Cy'];
  print(names.contains('Bo'));
  print(names.indexOf('Bo'));
}

Sorting and reversing

sort puts the numbers in order from smallest to largest. reversed with toList gives that order backwards.

void main() {
  var numbers = [3, 1, 2];
  numbers.sort();
  print(numbers);
  print(numbers.reversed.toList());
}

Empty and not empty

items holds no values, so isEmpty gives true. isNotEmpty gives false for the same list.

void main() {
  var items = [];
  print(items.isEmpty);
  print(items.isNotEmpty);
}

Splitting text into a list

split cuts the text at each comma. print shows the list of three pieces.

void main() {
  var text = 'a,b,c';
  var parts = text.split(',');
  print(parts);
  print(parts.length);
}

Example

void main() {
  var words = 'pear,apple,plum'.split(',');
  print(words);
  words.sort();
  print(words);
  print(words.contains('apple'));
  print(words.indexOf('plum'));
  words.add('fig');
  print(words);
  print(words.isNotEmpty);
}

Key points

  • Use add to put a value at the end of a list.
  • Use remove to take the first matching value out of a list.
  • Use contains to ask whether a value sits in a list.
  • Use indexOf to get the index of a value in a list.
  • Use sort to put the values of a list in order.
  • Use reversed with toList to get the values in reverse order as a new list.
  • isEmpty is true for a list with no values and isNotEmpty is true for a list with at least one value.
  • Use split on a text value to cut it at a separator and get a list of pieces.

In this example, split cuts the text at the commas and gives a list of three words. The first print shows that list. sort puts the words in order and the next print shows the sorted list. contains gives true because apple sits in the list. indexOf gives 2 for plum. add puts fig at the end and the next print shows four words. The last print shows true because the list is not empty.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

Which method puts a value at the end of a list?