INTRODUCTION
You may sometimes want to generate numbers from 1 to 10 and store them within a list. You can use a for loop and the append method to do so but if you want a cleaner and faster approach to doing so then this tutorial is for you. The tutorial will teach you how to use the generate method in dart along side the arrow head function to generate numbers from 1 to 10
CODE SAMPLE
void main(){
List<int> generateNumbers=List.generate(10,(index)=>index+1);
print ("The generated numbers are: ${generateNumbers});
}
EXPLANATION
void main() {
This is the main function — it’s where the program starts. Every Dart program needs a main()
function to run.
List<int> generateNumbers
-
This creates a list that will hold integers (whole numbers).
-
It's named
generateNumbers
.
List<int> generateNumbers = List.generate(10, (index) => index + 1);
10
→ this tells Dart: “I want a list with 10 items.”(index) => index + 1
→ this means:For each number from 0 to 9 (because index starts at 0),
-
Add 1 to it.
-
So the list will be:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
.
Note: index in the generate method is not a keyword it is an ordinary variable name. It can be replaced by any variable name
print("The generated numbers are: ${generateNumbers}");
This will display the list on the screen. It prints:
TRY IT YOURSELF
Now modify the program to generate numbers from 0 to 100 in step of 2.
CONCLUSION
The tutorial teaches you how to use the generate method along side the arrow function to generate numbers between 1 to 10 instead of using a loop and append method. The try it yourself section allows you to extend the program to print values from 1 to 100 but in step of 2.
Tags:
Dart