What is the List lastIndexWhere() method in Dart?

The lastIndexWhere() method is used to find the index of the last occurrence of an element that satisfies the given condition.

Syntax

int lastIndexWhere (bool test(E element), [ int start = 0 ]);

Parameter

It accepts a condition that can be searched in the list.

Return value

The method lastIndexWhere() returns the last index in the list that matches the given condition.

Note: It searches the list from the beginning of the index to the end. The index of the item is returned if found. Otherwise, it returns -1.

Code

The following code shows how to use the method lastIndexWhere() in Dart:

void main() {
// Creating list
final List<Map<String, dynamic>> _student = [
{"name": "Elisa", "id": "15GH023", "offeredCourse": 10},
{"name": "Maria", "id": "15GH086", "offeredCourse": 8},
{"name": "Joe", "id": "15GH007", "offeredCourse": 11},
];
// Find the last index where offeredCourse > 8
final foundIndex = _student.lastIndexWhere((e) => e["offeredCourse"] > 8);
// Display result
if (foundIndex != -1) {
print("Index $foundIndex: ${_student[foundIndex]}");
}
}

Explanation

  • Line 3-7: We create a list named _student.
  • Line 10: We use the method lastIndexWhere() to find the last index where offeredCourse > 8. It returns the index where offeredCourse > 8, which is then stored in variable foundIndex.
  • Line 13-14: First, we check the index value. If it is not -1, then we display the result.

Free Resources