📅  最后修改于: 2023-12-03 14:40:36.559000             🧑  作者: Mango
In this article, we will explore the last
method of Dart lists. We will learn how to use it to access the last element of a list and how to handle corner cases when the list is empty or null.
The last
method is defined in the List
class of the Dart standard library. Its syntax is as follows:
E last; // where E is the type of the list elements
Here, last
is a getter that returns the last element of the list. If the list is empty, it throws a StateError.
Let's see some examples of how to use the last
method.
void main() {
var numbers = [1, 2, 3, 4, 5];
var lastNumber = numbers.last;
print(lastNumber); // 5
}
In this example, we create a list of numbers and use the last
method to access the last element of the list.
void main() {
var emptyList = [];
try {
var lastElement = emptyList.last;
print(lastElement);
} on StateError catch (e) {
print('Caught StateError: $e');
}
}
In this example, we create an empty list and try to access its last element using the last
method. Since the list is empty, the last
method throws a StateError, which we catch and print to the console.
void main() {
List<int>? nullableList;
try {
var lastElement = nullableList!.last;
print(lastElement);
} on StateError catch (e) {
print('Caught StateError: $e');
}
}
In this example, we create a nullable list and try to access its last element using the last
method. Since the list is null, the null assertion operator (!) throws a NoSuchMethodError, which is caught and handled as a StateError.
The last
method of Dart lists is a useful way to access the last element of a list. It is important to handle corner cases when the list is empty or null to avoid runtime errors.