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.
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
}
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;
}
}
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