Dart Programming - List.single Method



Checks if the list has only one element and returns it.

Syntax

List.single 

Example

void main() { 
   var lst = new List(); 
   lst.add(12);
   print("The list has only one element: ${lst.single}"); 
}  

It will produce the following output

The list values in reverse order: (13, 12) 

It will produce the following output

The list has only one element: 12 

This property throws an exception if the List has more than one element in it. The following example illustrates the same −

void main() { 
   var lst = new List(); 
   lst.add(12); 
   lst.add(10); 
   print(lst.single); 
}

If the list has more than one element, then the same code will throw the following exception

Unhandled exception: 
Bad state: Too many elements 
#0 List.single (dart:core-patch/growable_array.dart:234) 
#1 main (file:///D:/Demos/Boolean.dart:6:13) 
#2 _startIsolate.<anonymous closure> (dart:isolatepatch/isolate_patch.dart:261) 
#3 _RawReceivePortImpl._handleMessage (dart:isolatepatch/isolate_patch.dart:148)
dart_programming_lists.htm
Advertisements