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,

  1. We create a list named numbers containing the integer 1.
  2. We use the single property to get the single element in the list.
  3. The single number is stored in singleNumber.
  4. 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,

  1. We create a list named characters containing the character 'a'.
  2. We use the single property to get the single element in the list.
  3. The single character is stored in singleCharacter.
  4. 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,

  1. We create a list named strings containing the string 'apple'.
  2. We use the single property to get the single element in the list.
  3. The single string is stored in singleString.
  4. 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.