Dart: create a list from 0 to N

Issue

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

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

Solution

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]
}

After Dart 2.3 you can use collection for:

var list = [for (var i = 1; i <= 10; i++) i];

Answered By – Alexandre Ardhuin

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.