📜  dart list last - Dart (1)

📅  最后修改于: 2023-12-03 14:40:36.559000             🧑  作者: Mango

Dart List Last

Introduction

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.

Syntax

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.

Usage

Let's see some examples of how to use the last method.

Example 1: Accessing the last element of a list
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.

Example 2: Handling an empty 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.

Example 3: Handling a null list
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.

Conclusion

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.