Get the first element of list if it exists in dart

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
}

Leave a Comment