Null-aware .firstWhere, .singleWhere, .lastWhere in Dart's List?
Solution 1
You can just use firstWhereOrNull which should work exactly as you expect.
Solution 2
The solution would be to create an extension on the Iterable
type:
extension IterableModifier<E> on Iterable<E> {
E? firstWhereOrNull(bool Function(E) test) =>
cast<E?>().firstWhere((v) => v != null && test(v), orElse: () => null);
}
Then use it like this:
final myList = <String?>['A', 'B', null, 'C'];
String? result = myList.firstWhereOrNull((e) => e == 'D');
print(result); // output: null
result = myList.firstWhereOrNull((e) => e == 'A');
print(result); // output: "A"
Try the full example on DartPad
![Marcin Wróblewski](https://i.stack.imgur.com/wtYwL.jpg?s=256&g=1)
Marcin Wróblewski
Updated on December 01, 2022Comments
-
Marcin Wróblewski over 1 year
I often use
.firstWhere((E element) -> bool) -> E
in my project. When porting it to support null safety I couldn't cleanly handle a scenario when an element is not found in a List instance..firstWhere
,.singleWhere
and.lastWhere
returnsE
, notE?
so when handling a case when a List does not contain required element there's no other way to returnnull
other than casting a whole list from eg.List<String>
toList<String?>
which makes testing function worried about each element being potentially null, which it can't be. Before null safety I was able to just useorElse: () => null
but with null safetyorElse
have to return element of typeE
so troublesome casting is required.Do I have to have a
null
substitute for each type to use inorElse
or are there other methods to make list checking support missing element scenario with null? -
Ebena107 over 2 yearsremember to import collection. ` import 'package:collection/collection.dart'; `