3

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

Maher Abuthraa
  • 17,493
  • 11
  • 81
  • 103
  • 1
    While I guess no one has posted this question about Dart yet, I must say this distinction is not all that subtle or surprising. It should be extremely familiar to anyone who has seen the analogous (and very widely-known) [LINQ](https://stackoverflow.com/questions/5031726/linq-where-vs-takewhile) and [Streams](https://stackoverflow.com/questions/46850689/how-is-takewhile-different-from-filter) APIs, and probably others. And it's pretty clear in the Dart documentation, too, as @jamesdlin showed us. – Noah May 05 '21 at 23:49

1 Answers1

7

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]
jamesdlin
  • 81,374
  • 13
  • 159
  • 204