Dart Set single
Syntax & Examples


Set.single property

The `single` property in Dart checks that this iterable has only one element, and returns that element.


Syntax of Set.single

The syntax of Set.single property is:

 E single 

This single property of Set checks that this iterable has only one element, and returns that element.

Return Type

Set.single returns value of type E.



✐ Examples

1 Getting the single number in a set

In this example,

  1. We create a set of integers called `numbers` with only one element.
  2. We use the `single` property to get the single element of the set.
  3. We then print the single number to standard output.

Dart Program

void main() {
  Set<int> numbers = {42};
  int singleNumber = numbers.single;
  print('Single number in the set: $singleNumber');
}

Output

Single number in the set: 42

2 Getting the single character in a set

In this example,

  1. We create a set of characters called `characters` with only one element.
  2. We use the `single` property to get the single element of the set.
  3. We then print the single character to standard output.

Dart Program

void main() {
  Set<String> characters = {'a'};
  String singleChar = characters.single;
  print('Single character in the set: $singleChar');
}

Output

Single character in the set: a

3 Getting the single word in a set

In this example,

  1. We create a set of strings called `words` with only one element.
  2. We use the `single` property to get the single element of the set.
  3. We then print the single word to standard output.

Dart Program

void main() {
  Set<String> words = {'hello'};
  String singleWord = words.single;
  print('Single word in the set: $singleWord');
}

Output

Single word in the set: hello

Summary

In this Dart tutorial, we learned about single property of Set: the syntax and few working examples with output and detailed explanation for each example.