Reputation: 3025
In dart, how to access the last element of a list?
var lst = ["element1" , "element2" , "element3"];
My list is dynamic.
Upvotes: 48
Views: 61801
Reputation: 11
Last element and last 10 element:
List<int> listNumber = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19];
int lastNumber = listNumber.last;
List<int> last10Number = [];
if(listNumber.length > 10){
for(int i=listNumber.length - 10; i < listNumber.length; i++){
last10Number.add(listNumber[i]);
}
}
print("$lastNumber\n");
last10Number.forEach((element)=> print(element));
Upvotes: 0
Reputation: 19
**//Dart Code: Find 1st, Last, 2nd last and 3rd last value in Array**
void main() {
List l1 = [1, 8, 5, 3, 0, 6, 7, 2, 9, 4,];
print('Our original Array: $l1');
// Sorting an array
l1.sort();
print('After sorting and Array: $l1');
//Now we find the first, last, 2nd and 3rd last values of array
var first = l1.first;
print('Last value of Array: $first');
var last = l1.last;
print('Last value of Array: $last');
var last2 =l1[l1.length-2];
print('Last value of Array: $last2');
var last3 =l1[l1.length-3];
print('Last value of Array: $last3');
}
Upvotes: 0
Reputation: 3025
you can use last
property for read/write, inherited-getter:
last
is a returns the last element from the given list.
var lst = ["element1" , "element2" , "element3"];
lst.last // -> element3
or
lst[lst.length-1] //-> element3
Upvotes: 95