For Loop
The for loop is one of the most commonly used loops in Dart. It's perfect when you know exactly how many times you want to repeat a block of code. Think of it like doing jumping jacks - you decide upfront "I'll do 20 jumping jacks" and then count from 1 to 20.
Basic Syntax
The for loop has three main parts:
for (initialization; condition; increment/decrement) {
// code to be executed
}
- Initialization: Set up a counter variable (usually
i) - Condition: Check if the loop should continue
- Increment/Decrement: Update the counter after each iteration
Simple Example
Let's print numbers from 1 to 5:
void main() {
for (int i = 1; i <= 5; i++) {
print('Number: $i');
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
How It Works
int i = 1- Initialize counter to 1i <= 5- Check if i is less than or equal to 5- If true, execute the code block
i++- Increment i by 1- Repeat steps 2-4 until condition becomes false
Different Patterns
Counting Backwards
void main() {
for (int i = 5; i >= 1; i--) {
print('Countdown: $i');
}
print('Blast off! 🚀');
}
Skip Numbers (Increment by 2)
void main() {
for (int i = 0; i <= 10; i += 2) {
print('Even number: $i');
}
}
Working with Lists
For loops are great for iterating through lists:
void main() {
List<String> fruits = ['apple', 'banana', 'orange', 'grape'];
for (int i = 0; i < fruits.length; i++) {
print('Fruit ${i + 1}: ${fruits[i]}');
}
}
Nested For Loops
You can put for loops inside other for loops to create patterns:
void main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
print('i = $i, j = $j');
}
}
}
This creates a 3x3 grid of combinations!
Common Use Cases
| Use Case | Example |
|---|---|
| Counting | Print numbers 1 to 100 |
| List processing | Calculate sum of all elements |
| Pattern creation | Draw shapes with asterisks |
| Repetitive tasks | Send emails to multiple recipients |
Pro Tips
- Use meaningful variable names instead of just
iwhen it makes sense - Be careful with the condition to avoid infinite loops
- Remember that list indices start from 0, not 1
- You can use
breakto exit early orcontinueto skip iterations