OneBite.Dev - Coding blog in a bite size

Add New Item In Array In Dart

Code snippet for how to Add New Item In Array In Dart with sample and detail explanation

Arrays in Dart, also known as Lists, can hold multiple items of varying data types. This article will guide you on how to add or insert new items in an array in Dart programming.

Code snippet for Adding New Item In Array

Below is a simple code snippet which demonstrates how to add an item to an Array (List) in Dart:

void main() {
    List<String> heroicTeams = ["Avengers", "Justice League", "X-Men"];
    print("Before Addition: $heroicTeams");

    // Adding a new item
    heroicTeams.add("Fantastic Four");
    print("After Addition: $heroicTeams");
}

Code Explanation for Adding New Item In Array

Let’s breakdown the above code:

  1. First, we declare a List named heroicTeams with a few items of String data type:
    List<String> heroicTeams = ["Avengers", "Justice League", "X-Men"];
  1. We print out the initial content of the List, which displays the original teams before any additions:
    print("Before Addition: $heroicTeams");
  1. The add method is then used to add a new item to the List. In this case, “Fantastic Four” is added to heroicTeams:
    heroicTeams.add("Fantastic Four");
  1. Finally, we print out the content of the List once more, demonstrating that “Fantastic Four” has been successfully added:
    print("After Addition: $heroicTeams");

After running the code, the output will be as follows:

Before Addition: [Avengers, Justice League, X-Men]
After Addition: [Avengers, Justice League, X-Men, Fantastic Four]

This clearly shows that “Fantastic Four” has been added to the original list, successfully demonstrating how to add a new item to an array (List) in Dart.

dart