What is difference between filtering: Where and takeWhile in Dart

Viewed 484

I see both of them (where and takeWhile) has the same function .. or I might miss something here!

1 Answers

The documentation for Iterable.where says:

Returns a new lazy Iterable with all elements that satisfy the predicate test.

The documentation Iterable.takeWhile says:

Returns a lazy iterable of the leading elements satisfying test.

(emphasis added).

In other words, Iterable.takeWhile will stop iterating once it reaches the first item that does not satisfy the test callback.

A concrete example:

var list = [1, 1, 2, 3, 5, 8];
print(list.where((x) => x.isOdd).toList()); // Prints: [1, 1, 3, 5]
print(list.takeWhile((x) => x.isOdd).toList()); // Prints: [1, 1]
Related