{

How to create a sequence number in a list in Dart or Flutter | Dart By Example


Generate a sequence of numbers in A List  Dart or Flutter  example

Sometimes, We need to generate a fixed list with a sequence of numbers from 0 to N. This article, Shows multiple ways to create a list of 0 to n numbers.

How to create a sequence of numbers list for a given number in Dart or Flutter

There are multiple ways we can create a sequence of numbers in a list

  • use list generate function

generate() function in a list creates a list with values generated with a given function.

Syntax:

List generate(length, Function,{growable})

The list is created with a length attribute. Function is a generator function logic to have the values in a list growable: false means the List is fixed in size.

Here is 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]
  • use Collections for collection for in dart is used to create a list with manipulation of 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

To summarize, It is easy to create a sequence of numbers in a list with list generate function and collection for with examples

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.