Is it possible to know when I am on the last element in a for loop?

Viewed 609

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?

2 Answers

There is no such way to do this with for-in/forEach style loop. Either use an iterator, a for loop with an index, or for this specific case you can use the String.join method:

var _finalString = _blocks.join('\n')

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
    }
}
Related