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
firstWhere method Null safetyReturns the first element that satisfies the given predicate test . Iterates through elements and returns the first to satisfy test . If no element satisfies test , the result of invoking the orElse function is returned. If orElse is omitted, it defaults to throwing a StateError.
The firstWhere method will loop through all the elements of the queue in the iteration order and check each element against the test condition. It will return the first element that satisfies the provided predicate function.
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
'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'); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With