How to create numbers from 1 to 10 using the Generate Method in Dart (With Code Sample)

 

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. 

Ameh Joseph Onyeke

Hello and welcome to my blog! My name is Ameh Joseph Onyeke a passionate educator and tech enthusiast with a BSc in Computer Science from Benue State University, a PGDE from the University of Maiduguri, and a Master’s in Software Engineering from Bayero University Kano. My journey blends a strong foundation in computing with a love for teaching, aiming to simplify complex tech concepts for learners at all levels. Through this blog, I provide answers and insights across 10+ programming languages to support students and tech enthusiasts in building their skills and confidence. Whether you're solving coding problems or sharpening your programming abilities, this blog is here to guide you. Let’s learn and grow together!

Post a Comment

Previous Post Next Post