In this Flutter post, we will see how to get and use Flutter for loop index using a practical Flutter example. Everything about Flutter for loop index will be discussed in detail so you can have a clear idea of how to use it in your own Flutter apps as well.
What is Flutter For Loop Index?
Flutter for loop index is actually used to get the values from lists in Flutter apps. We will take values from list using the Flutter for loop index. Let’s start understanding it by using a proper Flutter example.
Implementing Flutter For Loop Index(Example)
In order to implement Flutter for loop index, first understand how Flutter for loop works.
Syntax
for(variable;condition;increment) { //do something }
See the below steps:
- It starts with for keyword.
- In parenthesis, first an integer variable in defined. Then condition is applied to that integer and finally an increment to the value of integer.
- Body is defined as curly braces, anything write within these curly braces comes in the body of for loop.
Example
We will be using a list of items and fetch some specific value from that list using the Flutter for loop index. See below code:
List<dynamic> listOfValues=[ 'Circle', 'Rectangle', 34, 'Green', 'Car' ];
You can see that we have a list of dynamic type, means it can store any type of value. Let’s now use a Flutter for loop and search for the value of Green string.
We will first set the value of for loop to 0, the reason for that is the list items index start from 0. In the condition, we will use the list length and then increment that integer value by 1.
In the body section, we have used an if else statement. Reason is that the if statement will check if the current index is equal to the string Green then print that index value (list[integer]), if not then run the else block.
Let’s see practical code for this theory. See below code:
for(int i=0; i<listOfValues.length; i++) { if(listOfValues[i]=='Green'){ print(listOfValues[i]); break; } else{ print('Green not found yet'); } }
Output:
Green not found yet Green not found yet Green not found yet Green
Conclusion
To conclude, hope you now will easily use and customize Flutter for loop index in your own Flutter apps. I would be happy to receive your feedback on this post. Thank you for reading this Flutter post.