On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Creating a Queue
  4. 2. Both Ends
  5. 3. Processing Until Empty
  6. 4. Queue or List?
  7. Code Examples
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 054: Queues

DayExtra Topics
Lecture054 of 057
Estimated video length10 min
TargetDart 3.12
LevelBeginner

Think of the line at a ticket counter: people join at the back and are served from the front. A queue stores items the same way: first in, first out. Dart's Queue adds and removes at both ends quickly, which a List can't do as well.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lectures 011 (lists) and 020–021 (loops).


Learning Objectives

  • Import and create a Queue
  • Add to the back and front; remove from the front and back
  • Read first, last, length; check isEmpty
  • Process a queue in a loop until it's empty
  • Choose between a Queue and a List

1. Creating a Queue

Queue lives in the dart:collection library, so import it first:

dart
import 'dart:collection';

void main() {
  var line = Queue<String>();
  line.add('Ali');
  line.add('Sara');
  line.add('Hamza');
  print(line);   // {Ali, Sara, Hamza}
}

You can also start from a list: Queue.of([1, 2, 3]).

2. Both Ends

dart
var first = line.removeFirst();
print('Serving $first');   // Serving Ali
print(line);               // {Sara, Hamza}

line.addFirst('VIP Zara'); // jumps to the front
line.addLast('Bilal');     // same as add()
print(line);               // {VIP Zara, Sara, Hamza, Bilal}

print(line.first);         // VIP Zara
print(line.last);          // Bilal
print(line.length);        // 4
print(line.contains('Sara'));  // true

line.removeLast();
print(line);               // {VIP Zara, Sara, Hamza}
MethodDoes
add(x) / addLast(x)put x at the back
addFirst(x)put x at the front
removeFirst()take the front item out and return it
removeLast()take the back item out and return it
first / lastlook at an end without removing
length, isEmpty, isNotEmpty, contains(x)same as on a list

3. Processing Until Empty

A common pattern: keep taking from the front until nothing is left.

dart
while (line.isNotEmpty) {
  print('Next: ${line.removeFirst()}');
}
print(line.isEmpty);   // true

Output

code
Next: VIP Zara
Next: Sara
Next: Hamza
true

4. Queue or List?

You need…Use
items by position (items[3])List
to add or remove at the front oftenQueue
first-in, first-out processing (jobs, messages, a waiting line)Queue

Removing the first item of a long List has to shift every other item along. A Queue does it instantly.


Code Examples

Example 1: A Printer Queue

dart
import 'dart:collection';

void main() {
  var printQueue = Queue<String>();

  void addJob(String file) {
    printQueue.add(file);
    print('Queued: $file (${printQueue.length} waiting)');
  }

  void printNext() {
    if (printQueue.isEmpty) {
      print('Nothing to print');
      return;
    }
    print('Printing: ${printQueue.removeFirst()}');
  }

  addJob('report.pdf');
  addJob('photo.png');
  addJob('notes.txt');
  printNext();
  printQueue.addFirst('urgent-invoice.pdf');
  print('Urgent job added to the front');
  printNext();
  printNext();
  printNext();
  printNext();
}

Output

code
Queued: report.pdf (1 waiting)
Queued: photo.png (2 waiting)
Queued: notes.txt (3 waiting)
Printing: report.pdf
Urgent job added to the front
Printing: urgent-invoice.pdf
Printing: photo.png
Printing: notes.txt
Nothing to print

Jobs print in the order they arrived, except the urgent one, which addFirst put at the front.


Common Beginner Mistakes

1. Forgetting the import

dart
void main() {
  var q = Queue<int>();
}
code
Error: Method not found: 'Queue'.

Add import 'dart:collection'; at the top.

2. Using an index

dart
var q = Queue.of([1, 2, 3]);
print(q[0]);
code
Error: The operator '[]' isn't defined for the type 'Queue<int>'.

A queue has no positions. Use first, last or a loop, or use a List instead.

3. Removing from an empty queue

dart
var q = Queue<int>();
q.removeFirst();
code
Unhandled exception:
Bad state: No element

Check isNotEmpty first.


Practice Questions

  1. Which library must you import to use Queue?
  2. After add(1); add(2); addFirst(0);, what does the queue print as?
  3. What does removeFirst() return?
  4. Can you write queue[2]?
  5. You're building a chat app where messages are sent one by one in arrival order. Queue or List?

Practice Answers

  1. dart:collection
  2. {0, 1, 2}
  3. The item that was at the front, which is now removed.
  4. No. Queues have no index operator.
  5. Queue: first in, first out.

Key Takeaways

  • import 'dart:collection'; then Queue<T>() or Queue.of(list).
  • add/addLast and addFirst add; removeFirst and removeLast remove.
  • Queues are first-in, first-out and fast at both ends.
  • No index access; check isNotEmpty before removing.