Skip to main content

Command Palette

Search for a command to run...

Dart While Loop

Published
•2 min read•View as Markdown
Dart While Loop
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, the while loop is used to execute a block of code repeatedly as long as a specified condition is true. The syntax of a while loop is as follows:

while (condition) {
  // Statements to execute
}

Here's a breakdown of each part:

  • condition: This is the condition that is evaluated before each iteration of the loop. If the condition is true, the loop continues; otherwise, the loop terminates.

  • {...}: This block contains the statements to execute for each iteration of the loop.

Here's an example of using a while loop:

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

In this example:

  • var i = 0 initializes a variable i to 0.

  • i < 5 is the condition that is evaluated before each iteration. As long as i is less than 5, the loop continues.

  • print('Iteration $i') prints the value of i for each iteration.

  • i++ increments the value of i by 1 after each iteration.

The loop will execute five times, printing:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4

It's important to ensure that the condition in a while loop eventually becomes false; otherwise, you may end up with an infinite loop.

The while loop is useful when you don't know in advance how many times you need to execute the loop, and you want to continue looping until a certain condition is met.

More from this blog

Parth Chauhan's blog

87 posts

Learner, Accountant, Marketer, Programmer.