Dart List add()
Syntax & Examples


Syntax of List.add()

The syntax of List.add() method is:

 void add(E value) 

This add() method of List adds value to the end of this list, extending the length by one.

Parameters

ParameterOptional/RequiredDescription
valuerequiredthe value to add to the list

Return Type

List.add() returns value of type void.



✐ Examples

1 Add number to a list of numbers

In this example,

  1. We create a list numbers containing integers [1, 2, 3].
  2. We use the add() method to add the number 4 to the list.
  3. The updated list is then printed.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3];
  numbers.add(4);
  print(numbers); // Output: [1, 2, 3, 4]
}

Output

[1, 2, 3, 4]

2 Add character to a list of characters

In this example,

  1. We create a list characters containing characters ['a', 'b', 'c'].
  2. We use the add() method to add the character 'd' to the list.
  3. The updated list is then printed.

Dart Program

void main() {
  List<String> characters = ['a', 'b', 'c'];
  characters.add('d');
  print(characters); // Output: [a, b, c, d]
}

Output

[a, b, c, d]

3 Add string to a list of strings

In this example,

  1. We create a list strings containing strings ['apple', 'banana'].
  2. We use the add() method to add the string 'cherry' to the list.
  3. The updated list is then printed.

Dart Program

void main() {
  List<String> strings = ['apple', 'banana'];
  strings.add('cherry');
  print(strings); // Output: [apple, banana, cherry]
}

Output

[apple, banana, cherry]

Summary

In this Dart tutorial, we learned about add() method of List: the syntax and few working examples with output and detailed explanation for each example.