Dart List removeLast()
Syntax & Examples
Syntax of List.removeLast()
The syntax of List.removeLast() method is:
E removeLast()
This removeLast() method of List removes and returns the last object in this list.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
none | none | This method takes no parameters. |
Return Type
List.removeLast() returns value of type E
.
✐ Examples
1 Remove and print the last number in the list
In this example,
- We create a list named
numbers
containing the integers[1, 2, 3, 4, 5]
. - We then use the
removeLast()
method onnumbers
to remove and retrieve the last element. - The removed element is printed to standard output.
- We also print the remaining list after removal.
Dart Program
void main() {
var numbers = [1, 2, 3, 4, 5];
var removed = numbers.removeLast();
print('Removed element: $removed');
print('Remaining list: $numbers');
}
Output
Removed element: 5 Remaining list: [1, 2, 3, 4]
2 Remove and print the last character in the list
In this example,
- We create a list named
characters
containing the characters['a', 'b', 'c', 'd', 'e']
. - We then use the
removeLast()
method oncharacters
to remove and retrieve the last element. - The removed element is printed to standard output.
- We also print the remaining list after removal.
Dart Program
void main() {
var characters = ['a', 'b', 'c', 'd', 'e'];
var removed = characters.removeLast();
print('Removed element: $removed');
print('Remaining list: $characters');
}
Output
Removed element: e Remaining list: [a, b, c, d]
3 Remove and print the last string in the list
In this example,
- We create a list named
strings
containing the strings['apple', 'banana', 'cherry']
. - We then use the
removeLast()
method onstrings
to remove and retrieve the last element. - The removed element is printed to standard output.
- We also print the remaining list after removal.
Dart Program
void main() {
var strings = ['apple', 'banana', 'cherry'];
var removed = strings.removeLast();
print('Removed element: $removed');
print('Remaining list: $strings');
}
Output
Removed element: cherry Remaining list: [apple, banana]
Summary
In this Dart tutorial, we learned about removeLast() method of List: the syntax and few working examples with output and detailed explanation for each example.