Dart Lesson 8 - Loops | Dataplexa

Loops in Dart

In this lesson, you will learn about loops in Dart. Loops allow you to execute a block of code repeatedly until a condition is met.

Loops are essential for working with real data such as user lists, transactions, sensor readings, logs, files, and API responses.


Why Loops Are Important

Without loops, programs would require repetitive code, which is inefficient and error-prone.

Loops help you:

  • Process large datasets
  • Iterate through lists and collections
  • Automate repetitive tasks
  • Improve performance and readability

The for Loop

The for loop is used when the number of iterations is known.

Example: Calculate total sales for 7 days.

List dailySales = [1200, 950, 1100, 1300, 1250, 1400, 1600];
int totalSales = 0;

for (int i = 0; i < dailySales.length; i++) {
  totalSales += dailySales[i];
}

print("Total Weekly Sales: $totalSales");

This loop iterates through each sales value and accumulates the total.


The for-in Loop

The for-in loop is cleaner and safer when iterating over collections.

Example: Count total items sold.

List itemsSold = [5, 8, 6, 9, 7];
int totalItems = 0;

for (var item in itemsSold) {
  totalItems += item;
}

print("Total Items Sold: $totalItems");

This loop avoids index errors and improves readability.


The while Loop

The while loop runs as long as a condition remains true.

Example: Simulate user login attempts.

int attempts = 0;

while (attempts < 3) {
  print("Login attempt ${attempts + 1}");
  attempts++;
}

This loop stops automatically once the maximum attempts are reached.


The do-while Loop

The do-while loop executes at least once, even if the condition is false.

Example: Display menu at least once.

int menuOption = 0;

do {
  print("Displaying menu...");
  menuOption++;
} while (menuOption < 1);

This is useful for menus, prompts, and user-driven programs.


Using break in Loops

The break statement exits a loop immediately.

Example: Stop processing when a defective product is found.

List productIds = [101, 102, 103, 999, 104];

for (var id in productIds) {
  if (id == 999) {
    print("Defective product found");
    break;
  }
}

Using continue in Loops

The continue statement skips the current iteration and moves to the next one.

Example: Ignore invalid transactions.

List transactions = [500, -1, 300, -1, 700];

for (var amount in transactions) {
  if (amount < 0) {
    continue;
  }
  print("Processed amount: $amount");
}

This ensures only valid data is processed.


Nested Loops

Loops can be placed inside other loops.

Example: Monthly sales report (weeks × days).

List> weeklySales = [
  [200, 300, 250],
  [400, 350, 300]
];

for (var week in weeklySales) {
  for (var day in week) {
    print("Sale: $day");
  }
}

Nested loops are common in reports, tables, and analytics.


Performance Tip: Choose the Right Loop

Use:

  • for when index control is needed
  • for-in for clean collection iteration
  • while for unknown iteration counts

Efficient loop selection improves performance and readability.


📝 Practice Exercises


Exercise 1

Use a for loop to print numbers from 1 to 10.

Exercise 2

Calculate the sum of values in a list using a for-in loop.

Exercise 3

Use a while loop to count down from 5 to 1.


✅ Practice Answers


Answer 1

for (int i = 1; i <= 10; i++) {
  print(i);
}

Answer 2

List values = [10, 20, 30];
int sum = 0;

for (var v in values) {
  sum += v;
}

print(sum);

Answer 3

int count = 5;

while (count > 0) {
  print(count);
  count--;
}

What’s Next?

In the next lesson, you will learn about functions in Dart.

Functions allow you to organize loop logic into reusable, clean, and scalable code — a core skill for professional Dart developers.