What is the List add() method in Dart?

Overview

The add() method is used to add an element at the end of the list, extending the list’s length by one.

Syntax

list_name.add(
   E value
);

In the code block above, list_name is the name of the list.

Parameters

  • value: The element to be added to the list.

Return value

This method does not return anything.

Code

The following code snippet demonstrates how to use the add() method in Dart.

void main(){
// Create List fruits
List<String> fruits = ['Mango', 'Pawpaw', 'Avocado', 'Pineapple', 'Lemon'];
// Display result
print("Original list $fruits");
// Insert new item in the list
// using add()
fruits.add('Apple');
// Display result
print('The new list: ${fruits}');
// Add new element
fruits.add('Orange');
// Display result
print('The new list: ${fruits}');
}

If the add() method is applied on a null list, it will throw a NoSuchMethodError exception.

Free Resources