Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
list
lastindexwhere
method
communitycreator

What is the List lastIndexWhere() method in Dart?

Maria Elijah

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

dart
list
lastindexwhere
method
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring