Skip to main content

Command Palette

Search for a command to run...

Dart Loops

Published
•2 min read•View as Markdown
Dart Loops
P

I'm Computer Engineering Student. Learning Status DSA in Java, Dart Development, Python in Django Development. Best part is Communication Skills, Marketing, Accounting.

In Dart, loops are used to execute a block of code repeatedly until a specified condition is met. Dart provides several types of loops, including for, while, do-while, and for-in. Here's a brief overview of each type:

1. for Loop:

The for loop is used when you know the number of iterations required.

for (var i = 0; i < 5; i++) {
  print('Iteration $i');
}

2. while Loop:

The while loop is used when the number of iterations is not known beforehand and the loop continues until a specified condition is false.

var i = 0;
while (i < 5) {
  print('Iteration $i');
  i++;
}

3. do-while Loop:

The do-while loop is similar to the while loop, except it executes the block of code at least once before checking the condition.

var i = 0;
do {
  print('Iteration $i');
  i++;
} while (i < 5);

4. for-in Loop:

The for-in loop is used to iterate over elements of an iterable (like lists or maps).

var myList = [1, 2, 3, 4, 5];
for (var item in myList) {
  print(item);
}

Loop Control Statements:

Dart also supports loop control statements like break, continue, and return to control the flow within loops.

  • break: Terminates the loop immediately.

  • continue: Skips the rest of the loop's code for the current iteration and proceeds to the next iteration.

  • return: Exits the function enclosing the loop.

for (var i = 0; i < 5; i++) {
  if (i == 2) {
    continue; // Skips iteration 2
  }
  if (i == 4) {
    break; // Terminates the loop when i is 4
  }
  print('Iteration $i');
}

These are the basic loop constructs in Dart. Depending on the situation and the nature of your task, you can choose the appropriate loop type.

More from this blog

Parth Chauhan's blog

87 posts

Learner, Accountant, Marketer, Programmer.