How can I create easily a range of consecutive integers in dart? For example:
// throws a syntax error :) var list = [1..10];
Dart for range loop In the example, we use the for range to go through a list of numbers. We iterate through the list of numbers. The e is a temporary variable that contains the current value of the list. The for statement goes through all the numbers and prints their squares to the console.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With