Menu
Coddy logo textTech

Adding Elements

Part of the Fundamentals section of Coddy's Dart journey — lesson 52 of 94.

The add() method lets you add new elements to the end of a list. This is how you expand a list after creating it.

Create a list of fruits:

List<String> fruits = ['Apple', 'Banana'];
print(fruits);

Add a new fruit to the list:

fruits.add('Orange');
print(fruits);

After executing the above code, the output will be:

[Apple, Banana]
[Apple, Banana, Orange]
challenge icon

Challenge

Beginner

In this challenge, you'll practice adding elements to a list using the add method.

The code already has a list of favorite colors with three colors. Your task is to add a fourth color, 'Purple', to the list using the add method.

After adding the color, the program will print the updated list, which should look like this:

[Red, Blue, Green, Purple]

Cheat sheet

The add() method adds new elements to the end of a list:

List<String> fruits = ['Apple', 'Banana'];
fruits.add('Orange');
print(fruits); // [Apple, Banana, Orange]

Try it yourself

void main() {
  // List of favorite colors
  List<String> favoriteColors = ['Red', 'Blue', 'Green'];
  
  // TODO: Add 'Purple' to the favoriteColors list using the add method
  
  // Print the updated list
  print(favoriteColors);
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals