To remove elements from a list based on a condition in Dart, you can use the `removeWhere` method.
In this example,
numbers
with some elements.removeWhere
method along with a lambda function to remove elements greater than the threshold.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int threshold = 3;
numbers.removeWhere((num) => num > threshold);
print('Modified list after removing elements greater than $threshold: $numbers');
}
Modified list after removing elements greater than 3: [1, 2, 3]
In this example,
names
with some elements.isLongName
that returns true
if the length of the string is greater than a specified value.removeWhere
method along with the isLongName
predicate to remove elements matching the predicate condition.void main() {
List<String> names = ['John', 'Alice', 'Michael', 'Emma'];
int maxLength = 5;
bool isLongName(String name) => name.length > maxLength;
names.removeWhere((name) => isLongName(name));
print('Modified list after removing long names: $names');
}
Modified list after removing long names: [John, Alice, Emma]
In this tutorial, we learned How to Remove Element from List based on a Condition in Dart language with well detailed examples.