Dart Runes where()
Syntax & Examples

Runes.where() method

The `where` method in Dart returns a new lazy Iterable with all elements that satisfy the predicate test.


Syntax of Runes.where()

The syntax of Runes.where() method is:

 Iterable<int> where(bool test(int element)) 

This where() method of Runes returns a new lazy Iterable with all elements that satisfy the predicate test.

Parameters

ParameterOptional/RequiredDescription
testrequiredA function that takes an integer element and returns true if the element satisfies the condition.

Return Type

Runes.where() returns value of type Iterable<int>.



✐ Examples

1 Filtering even numbers from a list of numbers

In this example,

  1. We create a list numbers containing integers.
  2. We use the where() method with a function that filters even numbers.
  3. We convert the resulting Iterable to a list and print it.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  Iterable<int> evenNumbers = numbers.where((element) => element % 2 == 0);
  print(evenNumbers.toList());
}

Output

[2, 4]

2 Filtering long words from a list of strings

In this example,

  1. We create a list words containing strings.
  2. We use the where() method with a function that filters words with length greater than 5.
  3. We convert the resulting Iterable to a list and print it.

Dart Program

void main() {
  List<String> words = ['apple', 'banana', 'cherry'];
  Iterable<String> longWords = words.where((word) => word.length > 5);
  print(longWords.toList());
}

Output

[banana, cherry]

3 Filtering numbers greater than 1 from a set of numbers

In this example,

  1. We create a set uniqueNumbers containing integers.
  2. We use the where() method with a function that filters numbers greater than 1.
  3. We convert the resulting Iterable to a list and print it.

Dart Program

void main() {
  Set<int> uniqueNumbers = {1, 2, 3};
  Iterable<int> filteredNumbers = uniqueNumbers.where((number) => number > 1);
  print(filteredNumbers.toList());
}

Output

[2, 3]

Summary

In this Dart tutorial, we learned about where() method of Runes: the syntax and few working examples with output and detailed explanation for each example.