Dart Searching Iterables
Searching an iterable asks questions about its values. The search methods answer with a matching value, a position, or a true or false.
Finding a value with firstWhere
The test checks each word in order. The first word longer than three letters is the answer.
void main() {
var words = ['oak', 'elm', 'maple', 'ash'];
var found = words.firstWhere((w) => w.length > 3);
print(found);
}A fallback with orElse
No word starts with the letter z, so the search finds nothing. The orElse function supplies the printed fallback instead.
void main() {
var words = ['oak', 'elm', 'ash'];
var found = words.firstWhere((w) => w.startsWith('z'),
orElse: () => 'none found');
print(found);
}Asking with any and every
The any call asks whether one value is negative. The every call asks whether all values are positive.
void main() {
var numbers = [3, -1, 4];
print(numbers.any((n) => n < 0));
print(numbers.every((n) => n > 0));
}Locating a value with indexWhere
The first value above ten sits at index two. Positions count from zero, as with list indexes.
void main() {
var numbers = [5, 8, 12, 3];
var position = numbers.indexWhere((n) => n > 10);
print(position);
}The only match with singleWhere
Exactly one number in the list is even. The singleWhere method returns that number.
void main() {
var numbers = [3, 8, 5, 7];
var only = numbers.singleWhere((n) => n % 2 == 0);
print(only);
}Example
void main() {
var names = ['Al', 'Bo', 'Cyd', 'Eli'];
var target = names.firstWhere((n) => n.length == 3, orElse: () => 'nobody');
var place = names.indexWhere((n) => n.length == 3);
print(target);
print(place);
}Key points
- The firstWhere method returns the first value that passes a test.
- The orElse parameter supplies a fallback value for the case where nothing matches.
- The any method returns true when at least one value passes the test.
- The every method returns true only when all values pass the test.
- The indexWhere method returns the position of the first match, or -1 when nothing matches.
- The singleWhere method returns the one matching value and fits a list with exactly one match.
In this example, firstWhere scans the names for one with three letters and finds Cyd. The indexWhere call runs the same test and reports the position of that name. Cyd sits at index two.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What does indexWhere return when no value passes the test?