Reputation: 18622
I was wondering if there is a way to access the first element of a list in dart if an element exists at all, and otherwise return null.
First, I thought this would do the job:
final firstElement = myList?.first;
This works if myList is null or myList.length > 0, but would give me an error if myList is an empty List.
I guess I could do something like this:
final firstElement = (myList?.length ?? 0) > 0 ? myList.first : null;
But I was wondering if there is a simpler way of doing what I'm trying to do out there.
Upvotes: 36
Views: 40818
Reputation: 130
Note List<T>.firstOrNull
is available in Dart >= 3.0.0, package:collection
no longer required.
Upvotes: 3
Reputation: 8025
UPDATE: since Dart 3.0, package:collection
is no longer required to use method firstOrNull
. Thanks to @Mrb83 for pointing this out.
Now you can import package:collection
and use the extension method firstOrNull
import 'package:collection/collection.dart';
void main() {
final myList = [];
final firstElement = myList.firstOrNull;
print(firstElement); // null
}
Upvotes: 89
Reputation: 16080
For Dart 2.12 (with null-safety) adding an extension function might be a good idea:
extension MyIterable<T> on Iterable<T> {
T? get firstOrNull => isEmpty ? null : first;
T? firstWhereOrNull(bool Function(T element) test) {
final list = where(test);
return list.isEmpty ? null : list.first;
}
}
Upvotes: 16
Reputation: 1877
As you may have already guessed, you need to implement such functionality yourself and since this and/or this are still open, there is no minimalistic version of doing it (i.e. through extension functions).
So we should do the longer version:
E firstOrNull<E>(List<E> list) {
return list == null || list.isEmpty ? null : list.first;
}
Edit: As mentioned by @Mattia there will be support for static extension functions in version 2.6 (currently in beta).
Upvotes: 1