Finding with 'firstWhere'
Part of the Logic & Flow section of Coddy's Dart journey — lesson 15 of 65.
When you need to find a specific element in a list that meets certain criteria, the firstWhere() method provides an efficient solution. Unlike filtering methods that return all matching elements, firstWhere() stops searching as soon as it finds the first element that satisfies your condition.
The firstWhere() method takes a test function that returns true or false for each element. It examines elements one by one until it finds the first one that passes the test, then immediately returns that element.
List<int> numbers = [1, 3, 8, 15, 22, 7];
// Find the first even number
int firstEven = numbers.firstWhere((number) => number % 2 == 0);
print(firstEven); // 8For situations where no element matches your condition, firstWhere() provides an optional orElse parameter. This parameter accepts a function that returns a default value when no match is found, preventing your program from crashing with an error.
Challenge
EasyCreate a program that manages a customer service system by finding the first customer complaint that requires immediate attention. Your program should:
- Read a string input representing the department name
- Read multiple integer inputs representing complaint priority levels (the input will end when you receive
-1) - Read an integer input representing the urgent priority threshold
- Use the
firstWhere()method to find the first complaint with a priority level greater than or equal to the urgent threshold - Print the customer service results in the exact format shown below
For example, if the department name is "Technical Support", the priority levels are 3, 7, 2, 9, 4, and the urgent threshold is 8, your program should output:
Department: Technical Support
All complaints: [3, 7, 2, 9, 4]
Urgent threshold: 8
Searching for first complaint >= 8
First urgent complaint: 9
Status: Urgent complaint found - immediate action requiredIf the department name is "Billing Department", the priority levels are 4, 6, 3, 5, and the urgent threshold is 7, your program should output:
Department: Billing Department
All complaints: [4, 6, 3, 5]
Urgent threshold: 7
Searching for first complaint >= 7
First urgent complaint: Not found
Status: No urgent complaints - continue normal processingIf the department name is "Sales Support", the priority levels are 10, 2, 8, and the urgent threshold is 9, your program should output:
Department: Sales Support
All complaints: [10, 2, 8]
Urgent threshold: 9
Searching for first complaint >= 9
First urgent complaint: 10
Status: Urgent complaint found - immediate action requiredYour program must use the firstWhere() method to find the first complaint priority that is greater than or equal to the urgent threshold. If no urgent complaint is found, display "Not found" for the first urgent complaint and show "No urgent complaints - continue normal processing" as the status. If an urgent complaint is found, display the priority level and show "Urgent complaint found - immediate action required" as the status.
Cheat sheet
The firstWhere() method finds the first element in a list that meets a specific condition. It stops searching as soon as it finds a match and returns that element.
List<int> numbers = [1, 3, 8, 15, 22, 7];
// Find the first even number
int firstEven = numbers.firstWhere((number) => number % 2 == 0);
print(firstEven); // 8Use the orElse parameter to provide a default value when no element matches the condition:
// Returns a default value if no match is found
int result = numbers.firstWhere(
(number) => number > 100,
orElse: () => -1
);Try it yourself
import 'dart:io';
void main() {
// Read department name
String? department = stdin.readLineSync();
// Read complaint priority levels until -1
List<int> complaints = [];
while (true) {
int priority = int.parse(stdin.readLineSync()!);
if (priority == -1) break;
complaints.add(priority);
}
// Read urgent threshold
int urgentThreshold = int.parse(stdin.readLineSync()!);
// TODO: Write your code below
// Use firstWhere() method to find the first complaint >= urgentThreshold
// Output the results
print('Department: $department');
print('All complaints: $complaints');
print('Urgent threshold: $urgentThreshold');
print('Searching for first complaint >= $urgentThreshold');
// Print first urgent complaint result
// Print status message
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced List Manipulation
List Properties: first & lastList State: isEmpty & isNotEmpReversing a ListAdding to a List: insertList Removal: removeWhereFinding in a List: indexOfSorting a ListShuffling a ListRecap - List Organizer4Advanced Map Manipulation
Iterating Over a MapChecking for Keys and ValuesMap Properties: keys & valuesConditional Add: putIfAbsentRemoving Entries from a MapNested MapsRecap - Inventory Update2Functional List Operations
Transforming with 'map'Filtering with 'where'Using '.toList()'Checking Conditions with 'any'Conditions with 'every'Finding with 'firstWhere'Recap - Data Filtering5Project: Shopping Cart Calc
Project SetupAdding Items to the Cart3Sets
What is a Set?Creating a SetAdding and Removing from SetsChecking for Elements in a SetConverting a List to a SetSet UnionSet IntersectionSet DifferenceRecap - Unique Guest List