OneBite.Dev - Coding blog in a bite size

Loop Array In Dart

Code snippet for how to Loop Array In Dart with sample and detail explanation

Looping through an array is an essential skill to have when programming in Dart, the primary language used to develop applications in Flutter. This article provides a guide on how to loop through an array using Dart with a sample code snippet followed by an in-depth explanation.

Code snippet : Looping an Array in Dart

Here’s a simple example of how to loop through an array in Dart:

void main() {
  var array = [1, 2, 3, 4, 5];
  
  for (var item in array) {
    print(item);
  }
}

Code Explanation for Looping an Array in Dart

Let’s break down the above code bit by bit to understand how the loop array in Dart works.

void main() {

The void main() is the entry point of a dart program. We define our main program inside this function.

var array = [1, 2, 3, 4, 5];

This line declares an array variable called array, which contains five integer values.

for (var item in array) {

Then we come to the loop. The for...in loop is commonly used to iterate over elements in a collection such as a list (Dart’s version of an array). In this loop, the item variable will take on the value of each item in the array one at a time.

print(item);

Inside the loop, we have a simple print statement that prints the current value of item. Since item cycles through each element in the array, this will ultimately print out every number in the array.

  }
}

These are simply closing brackets for the for loop and the main() function.

The output of this script would be:

1
2
3
4
5

This is essentially how you loop through an array of items in Dart. The for...in loop is powerful and can be used with any iterable object to conveniently enumerate through each of its elements with minimal code.

dart