Where in Dart: Filtering Collections Using the where
Method#
About#
The where
method in Dart is used to filter elements in a collection based on a condition. It returns a new iterable that contains only the elements that satisfy the provided predicate (a boolean test). This is commonly used in lists, sets, and other iterable collections to extract elements that meet certain criteria without modifying the original collection.
How It Works#
The where
method takes a function as a parameter, known as a predicate, which evaluates each element of the collection. If the predicate returns true
, the element is included in the returned iterable. If it returns false
, the element is excluded.
- Input: A collection (e.g., List, Set) and a condition (predicate).
- Output: A filtered iterable with elements that satisfy the condition.
How to Use#
The where
method is called on an iterable collection, and you pass a function that defines the condition to filter elements. The method does not modify the original collection; it returns a new iterable instead.
Syntax:#
Iterable<E> where(bool test(E element));
test: A function that takes an element from the collection and returns true or false based on the condition you define.
Steps to use:#
- Define the condition in a function or use an inline anonymous function (lambda).
- Call where on the collection, passing in the condition function.
- The result is a filtered iterable, which can be converted to a list or set if needed.
Example#
Example 1: Filtering a List of Numbers Filter out numbers greater than 5 from a list of integers.
void main() {
List<int> numbers = [1, 2, 6, 8, 3, 5];
Iterable<int> filteredNumbers = numbers.where((num) => num > 5);
print(filteredNumbers.toList()); // Output: [6, 8]
}
Example 2: Filtering a Set of Strings#
Filter out strings that start with the letter ‘A’ from a set.
void main() {
Set<String> names = {'Alice', 'Bob', 'Alex', 'Charlie'};
Iterable<String> filteredNames = names.where((name) => name.startsWith('A'));
print(filteredNames.toList()); // Output: ['Alice', 'Alex']
}
In these examples, the where method is used to filter collections based on a custom condition. You can use this method to create new subsets of data without altering the original collection.