Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove item from list and return new list without removed item in flutter

Tags:

list

flutter

dart

I have a list of string as List<String> temp = ['a', 'b', 'c', 'd']; I want to modify and remove specific item from the list and return new list without the removed item.

For example, if I want to remove index 2, what I want to get is ['a', 'b', 'd'] removeAt doesn't work since it just returns removed string item...

like image 544
husky Avatar asked Jan 20 '26 11:01

husky


2 Answers

You can use cascade notation to return the list when you call removeAt.

void main() {
  print(['a', 'b', 'c', 'd']..removeAt(2));
}
like image 197
mmcdon20 Avatar answered Jan 23 '26 10:01

mmcdon20


temp.removeAt(index); is exactly what you want.

void main() {
  List<String> temp = ['a', 'b', 'c', 'd'];
  temp.removeAt(2);
  print(temp);
}

this function prints ['a', 'b', 'd'] which is what you wanted to get right?

but if you can also get the removed value with this.

void main() {
  List<String> temp = ['a', 'b', 'c', 'd'];
  var removedValue = temp.removeAt(2);
  print(removedValue);
}

If what you want is to get a clone of the original list but without the element you can create a new one like this.

  void main() {
  List<String> temp = ['a', 'b', 'c', 'd'];
  int indexToRemove = 2;
  List newList = temp.where((x) => temp.indexOf(x) != indexToRemove).toList();
  print(newList);
}
like image 25
Jaime Ortiz Avatar answered Jan 23 '26 11:01

Jaime Ortiz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!