'Is it possible to know when I am on the last element in a for loop?
I am looping through a list to extract data point, but would like to know when I am on the last element (a certain function that is run in the for loop should not be run when its the last element)
for(final eachLine in _blocks){
//
_finalString = _finalString + eachLine + '\n';
}
(I don't want to add \n) for the very last element, so I'd like to know when I'm on the very last element if its possible?
Solution 1:[1]
You can track the last item by knowing the length of the list.
final len = items.length;
int i = 0;
for(final item in items){
i++;
if(i == len){
// this is the last item
} else {
// go on
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hazem Monir |
