Null-aware .firstWhere, .singleWhere, .lastWhere in Dart's List?

Issue

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 returns E, not E? so when handling a case when a List does not contain required element there’s no other way to return null other than casting a whole list from eg. List<String> to List<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 use orElse: () => null but with null safety orElse have to return element of type E so troublesome casting is required.

Do I have to have a null substitute for each type to use in orElse or are there other methods to make list checking support missing element scenario with null?

Solution

You can just use firstWhereOrNull which should work exactly as you expect.

Answered By – nvoigt

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.