Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: create a list from 0 to N

Tags:

list

range

dart

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

// throws a syntax error :) var list = [1..10]; 
like image 842
Cequiel Avatar asked Jun 13 '16 20:06

Cequiel


People also ask

How do you use a range in darts?

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.


1 Answers

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]; 
like image 180
Alexandre Ardhuin Avatar answered Sep 19 '22 21:09

Alexandre Ardhuin