DEV Community

Cover image for How to use loops in dart programming language.
Ibrahim Enemona Abdulrasheed
Ibrahim Enemona Abdulrasheed

Posted on

How to use loops in dart programming language.

Understanding the types of loops in Dart and how to use them.

Prerequisites
To test this code, you should be able to access Dartpad.dev or have a Dart SDK platform where you can run this code.

What are loops?

The loop is a function of code that allows you to run a desired request repeatedly until an outcome is achieved.
Loops work by checking the given condition and repeating the process until that condition is met.

Types of loops in dart.

  1. For loop.
  2. While loop.
  3. Do-while loop (A type of while-loop).
  4. For-in loop (A type of for-loop).
  5. For-each loop (A type of for-loop).

For loop.

For loop example .

In the main function, we created the for loop by using the for keyword.
We then proceeded by creating an integer variable named I and assigned 0 to it.
The condition here states that i < 5; i++ for i is less than 5 adding 1. This means as long as I is less than 5 add 1.

Here is the output.

For loop output

While loop.
In this type of loop, it is written with the keyword while before the condition.
On every iteration, the loop checks the condition.

While loop example

While(condition){}

Here is the output.

While loop output .

Note: Avoid writing a condition that is always true to avoid falling into an infinite loop.

Do-while loop.
Just as the name indicates, it's simply do-while. It carries the function first before checking the condition.

Do-while loop example

The condition is placed last in this type of loop. It is executed at least once.

Here is the result

Do-while loop output .

For-in loop.
For-in loop is used to loop through the properties of an object.
This loops through the properties in order.

For-in loop example

For everything in this variable

Here is the output.

For-in loop output

For each loop.

In this type of loop, you can simplify the for-in loop.
The for-each loop applies to collections.
For Example.

For-each loop example

Here is the output.

For-each loop output

Top comments (2)

Collapse
 
oyenet1 profile image
Bowofade Oyerinde

Good one. It also resemble Javascripts. Nice one

Collapse
 
rashtech profile image
Ibrahim Enemona Abdulrasheed

It does. Thank you 😊