For in Dart
Dart provides several ways to create loops. Here are some basic types of loops in Dart.
To run the program, save it as for_loops.dart
and use the dart
command:
In Dart, we use while
loops for the most basic type of loop with a single condition. The classic C-style for
loop is also available.
Instead of using range
like in some other languages, Dart uses the for-in
loop to iterate over collections or ranges. To create a range of numbers, we use Iterable<int>.generate()
.
Dart doesn’t have an exact equivalent to a for
loop without a condition, but we can achieve the same result with a while (true)
loop and use break
to exit.
The continue
statement works the same way as in many other languages, allowing you to skip to the next iteration of the loop.
We’ll see some other loop forms later when we look at for-in
statements with collections and other data structures.