Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart Map comprehension

Tags:

dart

In python I'd write:

{a:0 for a in range(5)}

to get

{0: 0, 1: 0, 2: 0, 3: 0, 4: 0}

How can I achieve the same in Dart?

So far I have this:

List<Map<String, double>>.generate(5, (i) => { i: 0 });

but this generates list of maps [{0: 0}, {1: 0}, {2: 0}, {3: 0}, {4: 0}],

while I want a simple map

like image 744
Marcin Avatar asked Jun 10 '26 22:06

Marcin


1 Answers

Dart has a collection for syntax that is similar to Python's comprehensions. The Dart Language Tour provides examples for Lists, but it can be used for Sets and Maps too:

final map = {for (var a = 0; a < 5; a += 1) a: 0};

You can consult the feature specification for more details.

like image 134
jamesdlin Avatar answered Jun 12 '26 11:06

jamesdlin