How to create a sequence number in a list in Dart or Flutter | Dart By Example
Sometimes, there’s a need to generate a fixed list containing a sequence of numbers from 0 to N. This article demonstrates multiple methods to achieve this in Dart or Flutter.
How to Create a Sequence of Numbers List for a Given Number in Dart or Flutter
There are several approaches to creating a sequence of numbers in a list.
- Using the generate() function
The generate()
function within a list creates a list with values generated by a specified function.
Syntax:
List generate(length, Function, {growable})
The list is created with a length
attribute. Function is a generator function logic to populate the list with values. The growable
parameter, when set to false, indicates that the List is fixed in size.
Here’s an example to create a list of sequence numbers from 0 to N.
void main() {
var sequenceNumbers = new List<int>.generate(20, (k) => k + 1);
print(sequenceNumbers);
}
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
- Using Collection For The
collection for
syntax in Dart is utilized to create a list by iterating over indexed values.
void main() {
var numberList = [for (var i = 1; i <= 20; i++) i];
print(numberList);
}
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Conclusion
In conclusion, creating a sequence of numbers in a list is straightforward with the generate()
function and collection for
in Dart, as demonstrated in the examples above.