How to remove item from list and return new list without removed item in flutter
3,702
Solution 1
You can use cascade notation (https://dart.dev/guides/language/language-tour#cascade-notation), to return the list when you call removeAt
.
void main() {
print(['a', 'b', 'c', 'd']..removeAt(2));
}
Solution 2
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);
}
Author by
husky
Updated on December 30, 2022Comments
-
husky about 1 year
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...