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?
CodePudding user response:
You can try the following solution by using import package:collection
and use the extension method firstOrNull: