Faris Shomali
Faris Shomali

Reputation: 141

How to remove the last three elements in a list using Dart?

if you have list like this ...

      List<String> data = ['1', '2', '3', '4', '5',..... n];

how can you remove the last three element knowing that you don't know the length of the list, i tried to use removeRange() but it didn't go well.

Upvotes: 3

Views: 2307

Answers (3)

Amirhossein kz
Amirhossein kz

Reputation: 43

You can use removeRange like this:

data.removeRange(data.length - 3, data.length);

Upvotes: 2

Randal Schwartz
Randal Schwartz

Reputation: 44056

And one more way:

void main(List<String> arguments) {
  var myList = List.generate(10, (n) => n);
  print(myList);
  myList.length -= 3;
  print(myList);
}

which results in:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6]

Yeah, I was pleased to see that it works!

Upvotes: 0

Ravindra S. Patil
Ravindra S. Patil

Reputation: 14775

Try below code

void main() {
  List data  = ['1', '2', '3', '4', '5'];
  data .length = data.length - 3;//put your how many list item you want to remove eg.1,2,3,...n
  print(data);
}

Result-> [1, 2]

Upvotes: 4

Related Questions