Dart List single
Syntax & Examples
Syntax of List.single
The syntax of List.single property is:
E single This single property of List checks that this iterable has only one element, and returns that element.
Return Type
List.single returns value of type E.
✐ Examples
1 Get the single number in the list
In this example,
- We create a list named
numberscontaining the integer1. - We use the
singleproperty to get the single element in the list. - The single number is stored in
singleNumber. - We print the single number to standard output.
Dart Program
void main() {
List<int> numbers = [1];
int singleNumber = numbers.single;
print('Single number: $singleNumber'); // Output: Single number: 1
}Output
Single number: 1
2 Get the single character in the list
In this example,
- We create a list named
characterscontaining the character'a'. - We use the
singleproperty to get the single element in the list. - The single character is stored in
singleCharacter. - We print the single character to standard output.
Dart Program
void main() {
List<String> characters = ['a'];
String singleCharacter = characters.single;
print('Single character: $singleCharacter'); // Output: Single character: a
}Output
Single character: a
3 Get the single string in the list
In this example,
- We create a list named
stringscontaining the string'apple'. - We use the
singleproperty to get the single element in the list. - The single string is stored in
singleString. - We print the single string to standard output.
Dart Program
void main() {
List<String> strings = ['apple'];
String singleString = strings.single;
print('Single string: $singleString'); // Output: Single string: apple
}Output
Single string: apple
Summary
In this Dart tutorial, we learned about single property of List: the syntax and few working examples with output and detailed explanation for each example.