In Dart, how do I get the first item of a List or null, if empty?

Viewed 48

Every time I want the first item or null, I do this:

final paragraphNodes = findNodes(node, (p) => p.type == 'p');
final paragraphNode = paragraphNodes.isNotEmpty ? paragraphNodes.first : null;

I could use Iterable.first but it doesn't return null, it throws an exception.

// `first` throws an exception if the list is empty
final paragraphNodes = findNodes(node, (p) => p.type == 'p').first;

How do I, in one line, return the first item of a list, or null?

1 Answers
Related