Ketuf Wtf
Ketuf Wtf

Reputation: 11

Dart how to remove elements from the list untill the last element of the list

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']

Upvotes: 0

Views: 2525

Answers (2)

jamesdlin
jamesdlin

Reputation: 89956

List.length is not just a getter; it's also a setter, and it can be used to truncate a List (or to grow one with nullable elements):

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

Upvotes: 5

Naslausky
Naslausky

Reputation: 3768

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.

Upvotes: 1

Related Questions