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

Python Is Rad
2 min readApr 25, 2020

--

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:

var int_list = [1, 2, 3, 4];

Python’s:

[x + 1 for x in my_list]

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

var int_list_plus_1 = int_list.map((x) => x + 1).toList();

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.

Python’s:

[x + 10 for x in int_list if x % 2 == 1]

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

var odd_list_plus_10 = int_list.where((x) => x % 2 == 1).map((x) => x + 10).toList();

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.

var str_list = ['a', 'b', 'c', 'ab', 'aa']

Python’s:

[x for x in str_list if x.startswith('a')]

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

var str_list_starts_a = str_list.where((x) => x.startsWith('a')).toList();

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.

var sorted_list_starts_a = str_list.where((x) => x.startsWith(‘a’)).toList()..sort();

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.

--

--

Python Is Rad

Python Is Rad. I’m a software engineer with an addiction to building things with code. https://twitter.com/PythonIsRad