Moritz
Moritz

Reputation: 10352

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

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.

Upvotes: 28

Views: 36862

Answers (6)

sahil prajapati
sahil prajapati

Reputation: 544

Answer given by Lars Tackmann was absolutely right but now this method not available in DART. Watch new method insert and insertAll.

void main() {

    final list = [1,2,3,4,5,6,7,8]; 
    
    // insert at particular indexed
    list.insert(2,50); // (index,value)
    // output : [1, 2, 50, 3, 4, 5, 6, 7, 8]
    //  as you sow value 50 inserted at index 2 
    
    final list2 = [1,2,3,4,5,6,7,8]; 
    // insert list inside list at perticular indexed 
    final allList = [11,22,33]; 
  
    // allList add at index = 3 in list2 
    list2.insertAll(3,allList); 
    
    // output : [1, 2, 3, 11, 22, 33, 4, 5, 6, 7, 8]  
    
}

Upvotes: 3

Khaled Mahmoud
Khaled Mahmoud

Reputation: 343

you can use

void insert(int index, E element);

Inserts all objects of [iterable] at position [index] in this list. This increases the length of the list by the length of [iterable] and shifts all later objects towards the end of the list. The list must be growable. The [index] value must be non-negative and no greater than [length].

Upvotes: 2

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657546

Dart 2

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

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

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

Upvotes: 39

Rohan Taneja
Rohan Taneja

Reputation: 10707

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

Upvotes: 9

Lars Tackmann
Lars Tackmann

Reputation: 20865

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

Upvotes: 25

Moritz
Moritz

Reputation: 10352

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

Upvotes: 2

Related Questions