Dart List lastIndexOf()
Syntax & Examples


Syntax of List.lastIndexOf()

The syntax of List.lastIndexOf() method is:

 int lastIndexOf(E element, [int? start]) 

This lastIndexOf() method of List the last index of element in this list.

Parameters

ParameterOptional/RequiredDescription
elementrequiredthe element to find the last index of in the list
startoptionalif provided, the search will start from this index backwards

Return Type

List.lastIndexOf() returns value of type int.



✐ Examples

1 Find the last index of an element in a list of numbers

In this example,

  1. We create a list named numbers with elements [1, 2, 3, 4, 3, 2, 1].
  2. We then use the lastIndexOf() method to find the last index of the element 3 in numbers.
  3. The last index of 3 is printed to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 3, 2, 1];
  int lastIndex = numbers.lastIndexOf(3);
  print('Last index of 3: $lastIndex');
}

Output

Last index of 3: 4

2 Find the last index of an element in a list of characters

In this example,

  1. We create a list named characters with elements ['a', 'b', 'c', 'd', 'c'].
  2. We then use the lastIndexOf() method to find the last index of the element 'c' in characters.
  3. The last index of 'c' is printed to standard output.

Dart Program

void main() {
  List<String> characters = ['a', 'b', 'c', 'd', 'c'];
  int lastIndex = characters.lastIndexOf('c');
  print('Last index of "c": $lastIndex');
}

Output

Last index of "c": 4

3 Find the last index of an element in a list of strings

In this example,

  1. We create a list named words with elements ['apple', 'banana', 'cherry', 'apple'].
  2. We then use the lastIndexOf() method to find the last index of the element 'apple' in words.
  3. The last index of 'apple' is printed to standard output.

Dart Program

void main() {
  List<String> words = ['apple', 'banana', 'cherry', 'apple'];
  int lastIndex = words.lastIndexOf('apple');
  print('Last index of "apple": $lastIndex');
}

Output

Last index of "apple": 3

Summary

In this Dart tutorial, we learned about lastIndexOf() method of List: the syntax and few working examples with output and detailed explanation for each example.