filter method

List<T> filter(
  1. bool test(
    1. T element
    )
)

Creates a new List containing only the elements that satisfy the given test function.

The function takes a test parameter, which represents a function that tests each element in the Iterable. It creates a new List, result, and adds only the elements that are not null and satisfy the given test function.

Returns a new List containing only the elements that satisfy the test function.

Example:

List<int> numbers = [1, 2, 3, 4, 5];
List<int> evenNumbers = numbers.filter((number) => number % 2 == 0);
print(evenNumbers); // Output: [2, 4]

Implementation

List<T> filter(bool test(T element)) {
  final result = <T>[];
  forEach((e) {
    if (e != null && test(e)) {
      result.add(e);
    }
  });

  return result;
}