OneBite.Dev - Coding blog in a bite size

Get The Last Element Of Array In Dart

Code snippet for how to Get The Last Element Of Array In Dart with sample and detail explanation

When working with arrays in Dart, you may often find yourself needing to access the last element of an array. Dart provides an easy way to perform this operation, and this article provides a simple guide on how to do this.

Code snippet for Getting The Last Element Of Array In Dart

void main() {
  var array = [1, 2, 3, 4, 5];
  var lastElement = array.last;
  print(lastElement);
}

Code Explanation for Getting The Last Element Of Array In Dart

Dart has a built-in method named last that allows you to get the last element from an array also known as “list” in Dart.

The first line of our code starts with the void main() {} function, which is the entry point of our Dart program.

Next we define our array variable, var array = [1, 2, 3, 4, 5];. This is a list of integers with five elements.

In Dart, to get the last element from this array, we simply use the last method on our array: var lastElement = array.last;. The value of lastElement will now be the value of the last element in our array.

In this case, lastElement will be 5, as it is the last element in our predefined array.

Finally, we print out the lastElement by using the print function: print(lastElement);. If you run this code, the output in the console will be 5.

That’s it! You should now have a clear understanding of how to get the last element of an array in Dart.

dart