Filtering elements: where, takeWhile, and skipWhile

on Sunday, 26th of July, 2020

Filtering elements from a list, for our purposes, means making a new list out of only some of the elements from an original list. There are many different methods that achieve this for different cases. But, one of the most useful methods on lists is where. In addition to where, I will discuss takeWhile and skipWhile.

where is used to filter elements from a list which pass a "test" passed in in the form of a callback.

void main() {
  final words = ["hot", "dog", "phone", "coffee", "pig"];
  final threeLetterWords = words.where((String word) { 
      return word.length == 3 

Important notes:

  • where returns a new Iterable instance, and does not mutate the original list.
  • if no elements pass the "test", an empty iterable is returned. It will not throw an error.
  • Some other filtering, where-like methods -- like singleWhere and firstWhere, will throw an error if no element in the list satisfies the test.

takeWhile and skipWhile

These methods also return new Iterables, but they return entire sections of the original list, depending on which element in the list satisfies the test. In human words:

  • takeWhile(testCallback)
    • this will return every element in a list from index 0 to the element that first satisfies the test.
  • skipWhile(testCallback)
    • this will return every element in a list starting with the first element that passes the test to the final element in the list.

void main() {
  final numsFrom0To5 = [0, 1, 2, 3, 4, 5];
  final numsTo2 = numsFrom0To5.takeWhile((int n) => n <= 2);
  final numsFrom3To5 = numsFrom0To5.skipWhile((int n) => n <= 2);
As you may have guessed, `takeWhile` and `skipWhile` are extremely useful for _sorted_ lists, but for much else.

Try filtering a list yourself

Join thousands of Flutter developers.

Sign up for infrequent updates about Flutter and Dart.

You can get all this content and more in one place. Check out my new book Flutter in Action