Dart List lastIndexWhere()
Syntax & Examples


Syntax of List.lastIndexWhere()

The syntax of List.lastIndexWhere() method is:

 int lastIndexWhere(bool test(E element), [int? start]) 

This lastIndexWhere() method of List the last index in the list that satisfies the provided test.

Parameters

ParameterOptional/RequiredDescription
testrequireda function that returns true for the desired element
startoptionalthe index to start searching from, defaults to the end of the list

Return Type

List.lastIndexWhere() returns value of type int.



✐ Examples

1 Find the last index of an even number in the list

In this example,

  1. We create a list named numbers containing the numbers [1, 2, 3, 4, 5].
  2. We then use the lastIndexWhere() method with a test function that checks if the element is even.
  3. The method returns the last index of the even number in the list.
  4. We print the result to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  int lastIndex = numbers.lastIndexWhere((element) => element % 2 == 0); // Output: 3
  print('Last index of even number: $lastIndex');
}

Output

Last index of even number: 3

2 Find the last index of the character 'c' in the list

In this example,

  1. We create a list named characters containing the characters ['a', 'b', 'c', 'd', 'e'].
  2. We then use the lastIndexWhere() method with a test function that checks if the element is equal to 'c'.
  3. The method returns the last index of the character 'c' in the list.
  4. We print the result to standard output.

Dart Program

void main() {
  List<String> characters = ['a', 'b', 'c', 'd', 'e'];
  int lastIndex = characters.lastIndexWhere((element) => element == 'c'); // Output: 2
  print('Last index of character \'c\': $lastIndex');
}

Output

Last index of character 'c': 2

3 Find the last index of a string starting with 'b' in the list

In this example,

  1. We create a list named strings containing the strings ['apple', 'banana', 'cherry', 'banana'].
  2. We then use the lastIndexWhere() method with a test function that checks if the element starts with 'b'.
  3. The method returns the last index of the string starting with 'b' in the list.
  4. We print the result to standard output.

Dart Program

void main() {
  List<String> strings = ['apple', 'banana', 'cherry', 'banana'];
  int lastIndex = strings.lastIndexWhere((element) => element.startsWith('b')); // Output: 3
  print('Last index of string starting with \'b\': $lastIndex');
}

Output

Last index of string starting with 'b': 3

Summary

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