43

In dart, how to access the last element of a list?

var lst = ["element1" , "element2" , "element3"];

My list is dynamic.

2 Answers 2

85

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 
3
  • 12
    The best one is lst[lst.length-1] way because in the "last" property ,it loops through the list until the last element is got , so it will be slower way. Oct 29, 2020 at 3:57
  • 2
    @AvisekSSarma It depends on the collection type and implementation. If the collection elements are accessible by index there will be the same call for lst[lst.length-1]
    – Yuri H
    May 20, 2021 at 12:09
  • @AvisekSSarma "The last element of a list can be modified, unlike an Iterable. A list.last is equivalent to theList[theList.length - 1], both for getting and setting the value." from api.flutter.dev/flutter/dart-core/List/last.html
    – ggorlen
    Apr 12, 2023 at 5:38
0
    **//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');
  
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.