Queue
- Dart course
- Intermediate
- Lesson 44/116
- 5 min
Learn FIFO collections with Queue<T>.
Queue<T>
Queue<T> is a FIFO (first in first out) collection. It comes from the dart:collection library. Elements are added at the end and removed from the front.
Create a Queue with import 'dart:collection'; var queue = Queue<String>();. The addLast method appends to the end and removeFirst removes and returns the front element.
A Queue is ideal for tasks processed in order. It is used in printer queues, message queues and similar scenarios. This lesson teaches the basic operations.
Queue flow
When you add three elements to a Queue and remove them in turn the FIFO rule shows itself. The first added element leaves first. removeFirst gives one element per call and shrinks the queue.
Example: queue.addLast('A'); queue.addLast('B'); queue.addLast('C');. Now queue.removeFirst() returns 'A', the second call returns 'B'. queue.length shrinks after each removal.
This behavior mirrors real-life queues: the first person in line is served first. A Queue expresses this logic in code.
Practice Queue operations
Add import 'dart:collection'. Create a Queue<String>(). Add 'A', 'B', 'C' with addLast. Remove two elements with removeFirst and print each. Finally print the length.
Starter code
import 'dart:collection';
void main() {
// create a Queue<String>, add three elements with addLast
// remove two elements with removeFirst, print the length
}Sample solution
import 'dart:collection';
void main() {
var queue = Queue<String>();
queue.addLast('A');
queue.addLast('B');
queue.addLast('C');
print(queue.removeFirst());
print(queue.removeFirst());
print(queue.length);
}Expected output
A B 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does removeFirst return?
var q = Queue<String>();
q.addLast('A');
var x = q.removeFirst();- The last element
- The list
- It throws an error
- The first element Correct answer
Explanation: removeFirst removes and returns the front element of the queue.
2 Match the Queue methods
| Term | Meaning |
|---|---|
addLast(x) |
Append to end |
removeFirst() |
Remove from front |
Queue<String>() |
Creation |
dart:collection |
Library |
3 Add an element to the Queue
var queue = Queue<String>();
queue.____('A');
var queue = Queue<String>();
queue.addLast('A');
Explanation: addLast appends an element to the end of the queue.