Dart Lists: Looping over the Element of List

Dart Lists: Looping over the Element of List

Dart Lists: Going Through the Guest List

In the world of Dart Lists, looping is like greeting each guest at the party – you want to say hi to everyone and maybe even chat a bit. Let's see how to do this in simple terms!

1. For Each Loop: Friendly Handshakes

Imagine you're shaking hands with each guest at the party. The forEach loop in Dart lets you do just that – it goes through each element in the list, allowing you to perform an action for each one.

List<String> partyGuests = ['Alice', 'Bob', 'Charlie'];

partyGuests.forEach((guest) {
  print('Hello, $guest!');
});

Here, we're going through the partyGuests list, and for each guest, we print a friendly greeting. It's like personally welcoming each person to the party.

2. For Loop: Counting the Crowd

Now, let's say you want to count how many guests are at the party. A traditional for loop is like going through the guest list one by one and keeping a tally.

List<String> partyGuests = ['Alice', 'Bob', 'Charlie'];
int guestCount = 0;

for (int i = 0; i < partyGuests.length; i++) {
  guestCount++;
}

print('There are $guestCount guests at the party!');

Here, we use a for loop to go through each element and increase the guestCount. It's like counting heads as guests enter the venue.

3. While Loop: Keeping the Fun Going

A while loop is like partying until the last guest leaves. It keeps going as long as a certain condition is true.

List<String> partyGuests = ['Alice', 'Bob', 'Charlie'];
int i = 0;

while (i < partyGuests.length) {
  print('Dancing with ${partyGuests[i]}!');
  i++;
}

In this example, we're dancing with each guest until we've gone through the entire list. It's like keeping the fun alive until the party ends.

Looping over Dart Lists is like making sure you interact with every guest at the party. Whether it's shaking hands, counting heads, or dancing with each person, loops help you make the most of your guest list!

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!