Different ways to insert items to a list in dart

Different ways to insert items to a list in dart:

In dart, we have a couple of ways to insert single or multiple items to a list. In this post, we will learn all these ways with examples to insert one single or multiple items to a dart list.

Insert single item using add():

add method is defined as below:

void add(dynamic value)

It adds one item to the end of the list and it extends the size of the list by one. For example:

void main() {
  List givenList = [1,2,3];
  givenList.add(4);
  
  print(givenList);
}

It will add the number 4 to the end of the list. It will print the below output:

[1, 2, 3, 4]

Adding multiple values:

To add multiple values to a dart list, we can use addAll. This is defined as below:

void addAll(Iterable<dynamic> iterable)

It appends all items of the iterable to the end of the list. It extends the list by the number of objects in the iterable. It throws one UnsupportedError exception if the list is fixed length list.

Example:

void main() {
  List givenList = [1,2,3];
  givenList.addAll([4, 5, 6, 7]);
  
  print(givenList);
}

It will print:

[1, 2, 3, 4, 5, 6, 7]

Insert an item at an index:

The above methods inserts items at the end of a list. To add an item at a given index, we can use the below method:

void insert(int index, dynamic element)

This method insert the element at index position index. This value must be always positive, and should not be greater than the length of the list. It shifts the list items and arrange them in the final list based on the index where the element is added.

Example:

void main() {
  List givenList = [1,2,3];
  givenList.insert(0,0);
  
  print(givenList);
}

It will print:

[0, 1, 2, 3]

This program is inserting 0 at the start of the list.

Insert multiple items at an index:

We can insert multiple items at an index using insertAll.

void insertAll(int index, Iterable<dynamic> iterable)

It inserts all items of iterable at index position index. This index should be positive and shouldn’t be greater than the length of the list. It shifts and adjusts the list length accordingly after the insertion is done.

Example:

void main() {
  List givenList = [1,2,3];
  givenList.insertAll(0,[-3,-2,-1,0]);
  
  print(givenList);
}

It will print:

[-3, -2, -1, 0, 1, 2, 3]

You might also like: