Everything you need to know about loop in Dart
Table of contents
Loops execute a code block until a specific condition is met. Here we will talk about for loops with while and do-while loop.
For loops
forEach() Loop
It's the method to iterate over each element of iterable whether it be a list, set, or map.
Example with list:
At first, we have to initialize the list of strings named “names”
The forEach() method is called on the names list. It takes a function as an argument, which is applied to each list element. In this case, the function is specified as a lambda expression (name) => print(name.toUpperCase()).
Output:
Example with map:
A map named 'names' is initialized and it contains string keys ("name", "Age", "Gender") and values of different types (String for name, int for age, and String for gender).
The forEach() method is called on the names map. It takes a function as an argument, which is applied to each key-value pair of the map. In this case, the function is specified as (key, value) { print("$key: $value"); }.
This function takes two parameters: key and value, representing each key-value pair in the names map. Inside the function body, "$key: $value" is used to concatenate the key and value into a string and print it.
Output:
For-in loop
It is a convenient and commonly used construct in Dart for iterating over elements of iterable objects. It's particularly useful when you only need to access the elements sequentially without requiring index manipulation.
Example with list
At first, the List is initiated with the name “details” which has stored dynamic data.
List iterates over each element in the details list. It declares a variable detail of type dynamic to represent each element in the list. The loop then prints each element using print(detail).
The dynamic type allows elements of any type to be stored in the list. However, it's important to note that using dynamic should be done with caution, as it bypasses static type checks at compile time, potentially leading to runtime errors if the wrong type is used with the elements.
Output:
Example for map
Iterates over Map using entries:
You can use the ‘entries’ property of the map to iterate over both the keys and values as key-value pairs by using nameOfMap.entries property. The data of key is extracted with val.key and value is extracted by val.value where val represents each element during each iteration of the loop.
Output:
Iterate over keys:
You can use the ‘keys’ property of the map to iterate over just the keys by using nameOfMap.keys.
Output:
Iterate over values:
You can use the ‘values’ property of the map to iterate over just the values by using nameOfMap.values.
Output:
for loop
It helps to repetitively run the code block based on certain conditions.
List<String>: Declares a list of strings. This means that the variable names can only hold a collection of strings.
names: The name of the variable being declared.
for(int i=0; i< names.length; i++): This is a classic for loop structure in Dart.
int i=0: Initializes the loop variable i to 0.
i<names.length: Specifies the loop condition. The loop will continue iterating as long as i is less than the length of the names list.
i++: Increments the loop variable i by 1 after each iteration.
print(names[i]): This statement prints the element of the names list at index i during each iteration of the loop.
Output:
while loop:
'while' loop is a control flow statement that allows you to execute a block of code repeatedly as long as a specified condition evaluates to 'true'
List<String>: Declares a list of strings. This means that the variable 'names' can only hold a collection of strings.
int index = 0 Initializes the variable 'index' to 0. This variable will be used to access elements of the names list.
while(index < names.length){ ... }: This is a while loop. It will continue executing the block of code inside the curly braces as long as the condition index < names.length is true.
print(names[index]);: This statement prints the element of the names list at the current value of index.
index++ This statement increments the value of index by 1 after each iteration of the loop.
Output:
do-while loop:
Example using set:
It declares a set named 'num' containing integers.
Then an integer variable 'index' is declared and initialized to 0. This variable will be used as an index to access elements of the set num.
Then a do-while loop is used. It will execute the code inside the curly braces at least once, and then continue to execute it as long as the condition inside the while statement is true. In this case, the condition is 'index<num.length', which means the loop will continue as long as index is less than the length of the set num.
Inside the loop, this line prints the element at the current index position of the set num, multiplied by 2. elementAt(index) is a method that retrieves the element at the specified index in the set.
After each iteration of the loop, the value of index is incremented by 1. This ensures that in each iteration, the loop will access the next element of the set.
Output:
Example using map
At first, a map named 'details' is initialized where the keys are of type String and values are of type int. It contains three key-value pairs representing names and ages.
An integer variable named 'index' is initialized and sets its initial value to 0. This variable will be used to access elements from the list of keys.
Then it retrieves all the keys from the details map and converts them into a list of strings. This list will be used to iterate over the keys of the map.
Inside the loop:
It retrieves the key at the current index from the keys list.
It prints a message indicating the name (key) and age (value) corresponding to that key from the details map.
It increments the index variable to move to the next key in the list.
The loop continues executing as long as the index is less than the length of the keys list.
Output: