Reputation: 7799
I would like to get the second to last item in a List
, similarly than with getter last
.
I tried the following :
final list = [1, 2, 3, 4, 5];
final secondToLast = (list..removeLast()).last; // Mutates the List
However it mutates the List
.
Upvotes: 2
Views: 5564
Reputation: 7799
There is many options available (however you should make sure that list is not null and has at least 2 elements) :
final list = [1, 2, 3, 4, 5];
// Works only for Lists
final secondToLast = list[list.length - 2];
final secondToLast = list.reversed.elementAt(1);
final secondToLast = list.reversed.skip(1).first;
// Works for any Iterable
final secondToLast = list.elementAt(list.length - 2);
To get something similar to last
, you can write an extension on Iterable
:
extension CustomIterable<T> on Iterable<T> {
T? get secondToLast {
return this == null || length < 2 ? null : elementAt(length - 2);
}
}
Upvotes: 8