Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i add an entry to a specific index in a list?

Tags:

dart

I can call list.add() which adds at the end but there is no convenient way to add an entry to a specific index which at the same time grows the list.

like image 642
Moritz Avatar asked Apr 01 '12 17:04

Moritz


People also ask

How do I add an item to a specific index in a list?

list.insert(index, elem) -- inserts the element at the given index, shifting elements to the right. list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().

How do you add to a specific index in Python?

Use the insert() function(inserts the provided value at the specified position) to insert the given item at the specified index into the list by passing the index value and item to be inserted as arguments to it.

How do you add an element to an Arraylist at a specific index in Python?

The insert() method inserts an element to the list at the specified index.


4 Answers

Dart 2

var idx = 3;
list.insert(idx, 'foo');

Depends on whether you want to insert a single item or a bunch of items

  • https://api.dartlang.org/stable/2.1.0/dart-core/List/insert.html
  • https://api.dartlang.org/stable/2.1.0/dart-core/List/insertAll.html

All available methods https://api.dartlang.org/stable/2.1.0/dart-core/List-class.html#instance-methods

like image 180
Günter Zöchbauer Avatar answered Oct 10 '22 09:10

Günter Zöchbauer


You can use insertRange, it will grow the list when adding new elements.

var list = ["1","3","4"];
list.insertRange(0, 1, "0");
list.insertRange(2, 1, "2");
list.forEach((e) => print(e));

You can try it out on the DartBoard here

like image 27
Lars Tackmann Avatar answered Oct 10 '22 11:10

Lars Tackmann


You can use the insert() and removeAt() methods now.

like image 9
Rohan Taneja Avatar answered Oct 10 '22 11:10

Rohan Taneja


Ok, it seams as if list.insertRange(index, range, [elem]) is what i am looking for.

like image 1
Moritz Avatar answered Oct 10 '22 10:10

Moritz