OneBite.Dev - Coding blog in a bite size

Insert An Element At A Specific Index In An Array In Dart

Code snippet for how to Insert An Element At A Specific Index In An Array In Dart with sample and detail explanation

Working with arrays is a crucial part of any programming language. Dart, which is commonly known for creating mobile, desktop, and web applications, provides impressive capabilities to handle arrays effectively. This article takes a closer look at how you can insert an element at a specific index in an array in Dart.

Code snippet to insert an element at a specific index in an array in Dart


void main() { 
   List<String> array = ["Dart", "Python", "Java"]; 
   print("Original Array: ${array}");
   
   array.insert(1, "C++");
   
   print("After inserting 'C++' at index 1: ${array}");
}

This Dart code snippet shows how to insert an element at a particular index in an array. Combined with the ‘insert’ method, you can quickly manipulate arrays to fit your specific requirements.

Code Explanation for inserting an element at a specific index in an array in Dart

Dart provides the ‘insert’ method to add an element at a specific index. You first need to specify an index then the element you want to add.

In the given code snippet,

  1. We first create a List object called ‘array’ that contains three elements: “Dart”, “Python”, “Java”.
List<String> array = ["Dart", "Python", "Java"]; 
  1. We then print the original array to display its initial state.
print("Original Array: ${array}");
  1. After that, we call the ‘insert’ method on the array and pass in the index where we want to insert an element and define the element (in this case, “C++”) we want to insert.
array.insert(1, "C++");

This line of code will insert “C++” at the index ‘1’ in the array. The index in Dart is zero-based, meaning the first element is at index ‘0’, the second element is at index ‘1’, and so forth.

  1. Finally, we print the array again to show the final state, where “C++” has been added at index ‘1’.
print("After inserting 'C++' at index 1: ${array}");

After running the program, it will output:

Original Array: [Dart, Python, Java]
After inserting 'C++' at index 1: [Dart, C++, Python, Java]

As you can see, adding an element to a specific index in an array in Dart is pretty straightforward. With this technique, you can easily manipulate Lists in Dart.

dart