Get the first element of list if it exists in dart

Viewed 18360

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.

3 Answers

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

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).

Related