Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

single
listqueue
dart
communitycreator

What is ListQueue.single property in Dart?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

ListQueue is a list based on Queue. Read more about ListQueue here.

The single property can be used to check if the ListQueue contains only one element. If the ListQueue contains only one element, then that element is returned.

If the ListQueue is empty or contains more than one element, a StateError is thrown.

Syntax

queue.single

Parameter

This property requires no parameters.

Return type

The property checks if there is only one element in the iterable and returns that element.

Code

The code below demonstrates how to check if the queue contains only one element.

import 'dart:collection';
void main() {
// create a queue
ListQueue queue = new ListQueue();
// add one element to the queue
queue.add(10);
print("queue is : $queue");
// check if the queue contains only one element
var ele = queue.single;
print("The single element in the queue is : $ele");
// add one more element
queue.add(20);
try {
print(queue.single);
} catch(e) {
print(e);
}
}
Using the single prroperty to check if the queue contians only one element

Explanation

In the code above:

  • In line 1, we import the collection library.

  • In line 4, we create a ListQueue with the name queue.

  • In lines 6, we use the add method to add the element 10 to the queue.

  • In line 9, we access the single property of the queue. This will check if the queue contains only one element. In our case, the queue contains only one element so that element is returned.

  • In line 12, we use the add method to add another element 20 to the queue. Now the queue contains two elements {10, 20}.

  • In line 14, we access the single property of the queue. This will check if the queue contains only one element. In our case, the queue contains two elements, so a StateError, saying Too many elements, is thrown.

RELATED TAGS

single
listqueue
dart
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring