To filter elements of a list based on a condition in Dart, you can use the where method along with anonymous functions (closures).
In this example,
numbers
with integer values.where
method along with an anonymous function to filter elements greater than a threshold value.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int threshold = 3;
var filteredNumbers = numbers.where((num) => num > threshold);
print('Filtered list: \$filteredNumbers');
}
Filtered list: (4, 5)
In this example,
words
with string values.where
method along with an anonymous function to filter elements containing a specific substring.void main() {
List<String> words = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
String substring = 'erry';
var filteredWords = words.where((word) => word.contains(substring));
print('Filtered list: \$filteredWords');
}
Filtered list: (cherry, elderberry)
In this tutorial, we learned How to Filter Elements of a List based on a Condition in Dart language with well detailed examples.