Dart Loops - 5 types of Loops You Must Know

| Page Views: 16

Dart Loops Tutorial and Examples.

Dart supports various types of loops. Let's explore them.

1. Standard For Loops

Here's an example:

main() {
  // A standard for loop
  for (var i = 0; i < 10; i++) {
    print(i);
  }
}

And we get:

0
1
2
3
4
5
6
7
8
9

2. For - in Loops

If you are working with a class that implements Iterable, then you can use the for-in loops.

Here's an example:

main() {
  var spaceprobes = ["Casini","James Web","Spitzer","Juno","WMAP", "Kepler","Swift"];
  for (var probe in spaceprobes) {
    print(probe);
  }

}

And we get:

Casini
James Web
Spitzer
Juno
WMAP
Kepler
Swift

3. forEach

Here's an example of forEach loop:

main() {
  var planets = ["Earth","Mercury","Saturn","Venus","Jupiter","Neptune", "Uranus","Mars"];
  planets.forEach((planet) => print(planet)); // invoke each callback

}

And we get:

Earth
Mercury
Saturn
Venus
Jupiter
Neptune
Uranus
Mars

This is a very commonly used looping construct. For example consider [a real world scenario where you are fetching data from database(/flutter/sqflite)]:

    Future fetchEveryone() async {
      List results = await _db.query("people", columns: Person.columns);
      List people = new List();
      results.forEach((map) {
        people.add(Person.fromMap(map));
     });
    return people;
    }

4. While Loops

While conditions in Dart, like in many other programming languages, are evaluated before the loop.

Here's a while loop example:

main() {
  var count = 1;

  while(count <= 10) {
    print("I love You Dart $count");
    count++;
  }

}

Result:

I love You Dart 1
I love You Dart 2
I love You Dart 3
I love You Dart 4
I love You Dart 5
I love You Dart 6
I love You Dart 7
I love You Dart 8
I love You Dart 9
I love You Dart 10

5. Do- While Loops

The do-while conditions are evaluated after the loop:

Here's an example:

main() {
  var count = 1;

  do {
    print("I love You Dart $count");
    count++;
  } while (count <= 10);
}

Result:

I love You Dart 1
I love You Dart 2
I love You Dart 3
I love You Dart 4
I love You Dart 5
I love You Dart 6
I love You Dart 7
I love You Dart 8
I love You Dart 9
I love You Dart 10

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post