Mon, Dec 26, 2022
Read in 2 minutes
In this post we take a look at "do" keyword with some example codes.
In Dart, ```do`` is a keyword that is used in conjunction with the
while` loop to create a loop that executes the loop body at least once before checking the loop condition.
The general syntax of a do-while
loop in Dart is as follows:
do {
// loop body
} while (condition);
In this syntax, the loop body is executed first, and then the condition is checked. If the condition is true, the loop body is executed again, and this continues until the condition becomes false.
Here is an example to illustrate the use of do
:
void main() {
int count = 0;
do {
print('Count is $count');
count++;
} while (count < 5);
}
In this example, we have created a do-while
loop that executes the loop body at least once, even if the condition is initially false. The loop body prints the value of count
to the console and increments the value of count
by 1. The loop continues to execute until count
is equal to 5.
When we run this code, we will see the following output:
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
In summary, the do
keyword in Dart is used in conjunction with the while
loop to create a loop that executes the loop body at least once before checking the loop condition. It is useful when you want to ensure that the loop body is executed at least once, even if the loop condition is initially false.