thumbnail

For Loop in Dart

Published on 29 March 2020
Last Updated on 29 March 2020

For loop is one of the control flow statements in Dart.

Use Of For Loop In Dart

A For loop is used for performing repeated execution of instructions. Using for loops in Dart, we can iterate over same set of instructions over and over again.

Simple For Loop

// for loop in dart
main(List<String> args) {
  for (var i = 0; i < 4; i++) {
    print('i is: ${i}');
  }
}

Above program produces following output:

i is: 0
i is: 1
i is: 2
i is: 3

For in loop in Dart

For in loop in Dart is used for iterating through object’s properties.

For more information, refer to following example.

// for in loop in dart
main(List<String> args) {
  var collection = [1, 2, 3];
  for (var obj in collection) {
    print('obj is ${obj}');
  }
}

Above program produces following output:

obj is 1
obj is 2
obj is 3

Above program demonstrates how we can iterate through elements in a list object through for in loop.

Nested For Loop in Dart

When one or more for loops are placed into one another then they are called nested for loops.

// nested for loop
main(List<String> args) {
  for (var i = 0; i < 3; i++) {
    for (var j = 0; j < 3; j++) {
      print('i is: ${i}, j is ${j}');
    }
  }
}

Above program produces following output:

i is: 0, j is 0
i is: 0, j is 1
i is: 0, j is 2
i is: 1, j is 0
i is: 1, j is 1
i is: 1, j is 2
i is: 2, j is 0
i is: 2, j is 1
i is: 2, j is 2

Process finished with exit code 0

While creating nested for loops one must make sure not to create an infinite loop.

Use of break statement in for loop

Once break is called inside a for loop, the program exits the loop. Subsequent statements placed after break statement are not executed.

// use of break in for loop
main(List<String> args) {
  for (var i = 0; i < 3; i++) {
    if (i == 3) {
      // for loop will exit when i becomes 3
      break;
    }
    print('i is: ${i}');
  }
}

Above program produces following output:

i is: 0
i is: 1
i is: 2

Use for continue statement in a for loop

Continue statement is used for skipping statements that are placed after the continue statement in the current iteration and returning program execution pointer back to the beginning of the loop.

// for loop continue
main(List<String> args) {
  for (var i = 0; i < 4; i++) {
    if (i == 2) {
      // for loop will skip execution when i becomes 2
      continue;
    }
    print('i is: ${i}');
  }
}

Above program produces following output:

i is: 0
i is: 1
i is: 3