An old time picture of a dart throwing team.
You can bet these swell chaps enjoy a finely crafted list comprehension in Dart. Photo by Museums Victoria on Unsplash

List Comprehensions in Dart

In my day job as a Python developer, I use list comprehensions a lot. Now that I’ve been doing some development in Dart, and more specifically Flutter, I wanted a place to reference the common list comprehension style executions in Dart. So here are a few good ones.

The Map() Method
Let’s start with a simple list of integers:


In Dart you would use the map() method like this:

Returns [2, 3, 4, 5]
The reason that I put the .toList() at the end is to get a List<int>. If you don’t, you end up with a MappedListIterable which is the return type from map().

The Where() Method
What about including a conditional Python if statement? Let’s return a list with only odd numbers incremented by 10.


In Dart you would use the where() and map() methods like this:

Returns [11, 13]
Not too bad. The where() method acts like an if statement, or sort of like Python’s filter().

The Where() Method on Strings
Now let’s use the where() method on a list of strings.


In Dart you would use the where() method like this:

Returns ['a', 'ab', 'aa']

Pretty cool.

Chaining and Cascade Notation
As you saw in the int_list.where().map() example above, you can chain some of these methods together. Let’s chain a sort() to Dart’s where() method. This one is interesting because you need to use a cascade notation that looks like two dots together ... The notation is necessary because the sort() returns void, and you can’t assign void to a variable.

Returns ['a', 'aa', 'ab']

Fun With Dart (and Flutter)
While I don’t find Darts list comprehension type methods as easy to use as Python’s, since I am now developing in Flutter I have learned to enjoy them.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Python Is Rad

Python Is Rad. I’m a software engineer with an addiction to building things with code.