Adding orElse function to firstWhere method
DartDart Problem Overview
I am trying to add the onElse function to the itterator.firstWhere method but I cannot get the syntax right.
I have tried something like
List<String> myList =
String result = myList.firstWhere((o) => o.startsWith('foo'), (o) => null);
But the compiler has an error of
> 1 positional arguments expected, but 2 found
I am sure it is a simple syntax problem, but it has me stumped
Dart Solutions
Solution 1 - Dart
In case someone came here thanks to google, searching about how to return null
if firstWhere
found nothing, when your app is Null Safe, use the new method of package:collection
called firstWhereOrNull
.
import 'package:collection/collection.dart'; // You have to add this manually, for some reason it cannot be added automatically
// somewhere...
MyStuff? stuff = someStuffs.firstWhereOrNull((element) => element.id == 'Cat');
About the method: https://pub.dev/documentation/collection/latest/collection/IterableExtension/firstWhereOrNull.html
Solution 2 - Dart
'orElse' is a named optional argument.
void main() {
checkOrElse(['bar', 'bla']);
checkOrElse(['bar', 'bla', 'foo']);
}
void checkOrElse(List<String> values) {
String result = values.firstWhere((o) => o.startsWith('foo'), orElse: () => '');
if (result != '') {
print('found: $result');
} else {
print('nothing found');
}
}
Solution 3 - Dart
void main() {
List<String> myList = ['oof'];
String result = myList.firstWhere((element) =>
element.startsWith('foo'),
orElse: () => 'Found nothing');
print(result);
}
Solution 4 - Dart
myObject = myList.firstWhere
((element) => element.myIdentifier == someIdentifier, orElse: ()=> null);