Dart: create a list from 0 to N
You can also use Dart's Iterable.generate function to create a range between 0..n-1
var list = Iterable<int>.generate(10).toList()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
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];
with dart 2.3.0 :
var list = [for(var i=0; i<10; i+=1) i];