Inserting Elements into a List


Advertisements

Mutable Lists can grow dynamically at runtime. The List.add() function appends the specified value to the end of the List and returns a modified List object. The same is illustrated below.

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

It will produce the following output

[1, 2, 3, 12]

The List.addAll() function accepts multiple values separated by a comma and appends these to the List.

void main() { 
   List l = [1,2,3]; 
   l.addAll([12,13]); 
   print(l); 
}

It will produce the following output

[1, 2, 3, 12, 13]

The List.addAll() function accepts multiple values separated by a comma and appends these to the List.

void main() { 
   List l = [1,2,3]; 
   l.addAll([12,13]); 
   print(l); 
} 

It will produce the following output

[1, 2, 3, 12, 13]

Dart also supports adding elements at specific positions in the List. The insert() function accepts a value and inserts it at the specified index. Similarly, the insertAll() function inserts the given list of values, beginning from the index specified. The syntax of the insert and the insertAll functions are as given below −

List.insert(index,value) 
List.insertAll(index, iterable_list_of _values)

The following examples illustrate the use of the insert() and insertAll() functions respectively.

Syntax

List.insert(index,value)  
List.insertAll([Itearble])

Example : List.insert()

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

It will produce the following output

[4, 1, 2, 3]

Example : List.insertAll()

void main() { 
   List l = [1,2,3]; 
   l.insertAll(0,[120,130]); 
   print(l); 
}

It will produce the following output

[120, 130, 1, 2, 3]
dart_programming_lists_basic_operations.htm
Advertisements