Google News
logo
Dart - Interview Questions
What are the different types of loops available in Dart?
In Dart, you can use several types of loops to iterate over a set of values or perform repetitive tasks. The different types of loops available in Dart are:

1. for loop : The `for` loop allows you to iterate over a sequence of values for a specified number of times. It consists of an initialization statement, a condition, and an iteration statement.
   for (var i = 0; i < 5; i++) {
     print(i);
   }​

   In this example, the `for` loop will iterate from 0 to 4, printing the values of `i` in each iteration.


2. for-in loop : The `for-in` loop is used to iterate over elements of an iterable object such as lists, sets, or strings.
   var myList = [1, 2, 3, 4, 5];
   for (var item in myList) {
     print(item);
   }​

   In this example, the `for-in` loop iterates over each element in the `myList` list and prints the values.


3. while loop : The `while` loop repeatedly executes a block of code as long as a given condition is true.
   var i = 0;
   while (i < 5) {
     print(i);
     i++;
   }​

   This example demonstrates a `while` loop that prints the values of `i` from 0 to 4.
4. do-while loop : The `do-while` loop is similar to the `while` loop, but the condition is checked after the code block is executed. This guarantees that the code block is executed at least once.
   var i = 0;
   do {
     print(i);
     i++;
   } while (i < 5);​

   In this example, the `do-while` loop prints the values of `i` from 0 to 4.

5. forEach loop : The `forEach` loop is used to iterate over elements of an iterable object and execute a function for each element.
   var myList = [1, 2, 3, 4, 5];
   myList.forEach((item) {
     print(item);
   });​

   This example uses the `forEach` loop to iterate over each element in the `myList` list and execute the provided function for each element.
Advertisement