Home > Software design >  Dart how to remove elements from the list untill the last element of the list
Dart how to remove elements from the list untill the last element of the list

Time:04-07

How to remove elements from a list untill the last element of the list for example:

['a', 'b', 'c', 'd']

with

list.removeRange(1, ??)

wóuld evolve in

['a', 'b']

CodePudding user response:

From the documentation you can see:

A range from start to end is valid if 0 ≤ start ≤ end ≤ length.

So you can use the list's length property:

On your example:

final list = ['a', 'b', 'c', 'd'];
list.removeRange(2, list.length);
print(list); // prints [a, b]

You can test it through DartPad here.

CodePudding user response:

List.length is not just a getter, it's also a setter:

void main() {
  var list = ['a', 'b', 'c', 'd'];
  list.length = 2;
  print(list); // Prints: [a, b]
}
  •  Tags:  
  • dart
  • Related