Dart: create a list from 0 to N

Cequiel picture Cequiel · Jun 13, 2016 · Viewed 34.2k times · Source

How can I create easily a range of consecutive integers in dart? For example:

// throws a syntax error :)
var list = [1..10];

Answer

Alexandre Ardhuin picture Alexandre Ardhuin · Jun 13, 2016

You can use the List.generate constructor :

var list = new List<int>.generate(10, (i) => i + 1);

You can alternativelly use a generator:

/// the list of positive integers starting from 0
Iterable<int> get positiveIntegers sync* {
  int i = 0;
  while (true) yield i++;
}
void main() {
  var list = positiveIntegers
      .skip(1)   // don't use 0
      .take(10)  // take 10 numbers
      .toList(); // create a list
  print(list);   // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}