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

Time:09-13

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:

Get the first element of list if it exists in dart

  • Related