![]() |
VOOZH | about |
A looping statement in Dart or any other programming language is used to repeat a particular set of commands until certain conditions are not completed. There are different ways to do so. They are:
The for loop in Dart is a powerful construct that closely mirrors the familiar for loop of Java, making it accessible to many developers. This loop is an essential tool for executing a block of code multiple times, and it’s particularly useful when you know in advance how many iterations you want to perform.
Syntax:
for(initialization; condition; text expression){
// Body of the loop
}
The control flow goes as:
Example:
Output:
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
The for...in the loop is a delightful feature in Dart that elegantly lets you iterate through the elements of a collection, such as lists or sets. It simplifies the process of accessing each element, allowing you to focus on what you want to do with the elements rather than the mechanics of looping.
Syntax:
for (var in expression) {
// Body of loop
}
Example:
Output:
1
2
3
4
5
The forEach loop is a handy way to navigate seamlessly through every single element in a collection.
Syntax:
collection.forEach((value) {
// Body of loop
});
Parameters:
Output:
1
2
3
4
5
The while loop keeps executing its block of code as long as the condition remains true. This loop is useful in scenarios where the number of times you need to repeat an action isn’t predetermined—perhaps you’re waiting for user input or monitoring a changing variable.
Syntax:
while (condition) {
// Body of loop
}
Example:
Output:
Hello Geek
Hello Geek
Hello Geek
Hello Geek
The do...while ensures that its block of code runs at least once before it even bothers checking the condition. Imagine committing to try something out first, and only after giving it a shot do you evaluate whether or not you want to continue. This makes the do...while loop particularly useful in situations where you want to execute some initial setup or action before validating any subsequent conditions.
Syntax:
do{
text expression;
// Body of loop
}while(condition);
Example:
Output:
Hello Geek
Hello Geek
Hello Geek
Hello Geek
In Dart, looping statements allow you to execute a block of code multiple times, either for a fixed number of iterations or based on a condition. Each type of loop serves a distinct purpose:
Selecting the appropriate loop depends on the specific problem, the data structure being used, and the requirements for control flow.