Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

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?

like image 547
André Pena Avatar asked Oct 22 '25 05:10

André Pena


1 Answers

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

like image 161
Yongjian P. Avatar answered Oct 26 '25 18:10

Yongjian P.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!