How To Easily Use While Loop In Flutter

while loop in Flutter

In this Flutter post, we will be explaining how to use while loop in Flutter with the help of an easy dart example. Everything will be explained step by step so you can also implement and customize in in your Flutter app with ease. So let’s get right into it.

What is While Loop In Flutter?

While loop is as the names suggests, it is a loop(repetition) having a condition on the start. You can specify to only run the body of while loop if a certain condition is met. Let’s practically understand while loop in Flutter with an easy dart language example.

Implementing While Loop In Flutter(Example)

let’s first understanding the basic syntax of while loop. See below:

Syntax

 while(condition)
{
      do some action
}

It starts with a while keyword, then a condition is specified in the parenthesis block. Finally, the body is specified with curly braces and inside it, we can specify any function we want.

Example

To demonstrate how while loop works in Flutter, we have specified a condition that if an integer values is less than 5, only then run whatever function is defined it in. We actually have defined a print function that will display the value of that integer and also an increment to that integer. It means every time the while body is executed, then the integer will get incremented by one value. See the below code:

int i=0;       //define an integer
while(i<5)       //condition will be checked
{
     print(i.toString()); //printing the value of integer
     i++;          //incrementing the integer   
}

Output:

0
1
2
3
4
You can see that the first value of integer was 0 and the condition is checked and it is true so the body of while loop is executed. The result is that we can see a 0 value in the above output section. Also an increment is made to that integer which means the value of integer is now 1 and the same process will take place again until the value of integer is 5. This will make the condition false and break the while loop as the condition was specified that only run the body of while loop if the value is less than 5.
So this is how you can easily use while loop in Flutter dart app.

Conclusion

To conclude this post, hope you now have a practical knowledge of how to use while loop in Flutter. I would love to have you feedback on this post. Thank you for reading.

Leave a Comment

Your email address will not be published. Required fields are marked *