Zeba Academy Priority Queue

pub package likes popularity license Dart Flutter

A lightweight, generic, and dependency-free priority queue for Dart and Flutter.

zeba_academy_priority_queue provides priority-based ordering with support for custom priority extraction, custom priority comparison, enqueue/dequeue operations, peeking, clearing, and length tracking.

✨ Features

  • πŸš€ Generic priority queue for Dart and Flutter
  • πŸ“Š Priority-based ordering
  • βž• Enqueue items
  • βž– Dequeue highest-priority items
  • πŸ‘€ Peek without removing
  • 🧹 Clear the queue
  • πŸ“ Track queue length
  • πŸ” isEmpty and isNotEmpty
  • βš™οΈ Custom priority extraction
  • πŸ”„ Custom priority comparator
  • ♻️ Supports duplicate priorities
  • πŸ“‹ Export queue contents with toList()
  • πŸ”’ Protects internal queue state
  • πŸͺΆ Lightweight implementation
  • πŸ“¦ Zero runtime dependencies
  • πŸ§ͺ Fully unit tested
  • πŸ’™ Flutter compatible

πŸ“¦ Installation

Add the package to your pubspec.yaml:

dependencies:
  zeba_academy_priority_queue: ^0.0.1

Then run:

flutter pub get

Or:

dart pub get

πŸš€ Getting Started

Import the package:

import 'package:zeba_academy_priority_queue/zeba_academy_priority_queue.dart';

Create a model:

class Task {
  const Task({
    required this.name,
    required this.priority,
  });

  final String name;
  final int priority;

  @override
  String toString() => '$name: $priority';
}

Create a priority queue:

final queue = ZebaPriorityQueue<Task>(
  priority: (task) => task.priority,
);

Add items:

queue.enqueue(
  const Task(
    name: 'Low priority task',
    priority: 1,
  ),
);

queue.enqueue(
  const Task(
    name: 'High priority task',
    priority: 10,
  ),
);

queue.enqueue(
  const Task(
    name: 'Medium priority task',
    priority: 5,
  ),
);

By default, higher priority values are processed first.

The queue is now ordered as:

High priority task   β†’ 10
Medium priority task β†’ 5
Low priority task    β†’ 1

πŸ‘€ Peek

Use peek() to inspect the highest-priority item without removing it:

final task = queue.peek();

print(task);

Output:

High priority task: 10

The queue length remains unchanged.

print(queue.length);

βž– Dequeue

Use dequeue() to remove and return the highest-priority item:

final task = queue.dequeue();

print(task);

Output:

High priority task: 10

Calling dequeue() again returns:

Medium priority task: 5

And then:

Low priority task: 1

When the queue is empty:

final task = queue.dequeue();

print(task); // null

🧹 Clear

Remove all items:

queue.clear();

After clearing:

print(queue.isEmpty); // true
print(queue.length);  // 0

πŸ“ Length

Get the current number of items:

print(queue.length);

Example:

queue.enqueue(task1);
queue.enqueue(task2);
queue.enqueue(task3);

print(queue.length); // 3

πŸ” Empty State

Check whether the queue is empty:

if (queue.isEmpty) {
  print('Queue is empty');
}

Check whether the queue contains items:

if (queue.isNotEmpty) {
  print('Queue contains items');
}

πŸ“‹ Get Queue Contents

Use toList() to retrieve the current priority order:

final tasks = queue.toList();

for (final task in tasks) {
  print(task);
}

The returned list is unmodifiable, so modifying it does not modify the queue.

final tasks = queue.toList();

tasks.add(
  const Task(
    name: 'Another task',
    priority: 20,
  ),
);

The above operation throws UnsupportedError.

βš™οΈ Custom Priority Extraction

The queue works with any generic type as long as you provide a way to determine its priority.

For example:

class Job {
  const Job({
    required this.title,
    required this.level,
  });

  final String title;
  final int level;
}

Create the queue:

final jobs = ZebaPriorityQueue<Job>(
  priority: (job) => job.level,
);

Now the queue automatically uses level to determine ordering.

πŸ”„ Custom Priority Comparator

By default, higher numeric priority values are processed first.

For example:

10 β†’ first
5  β†’ second
1  β†’ third

You can reverse this behavior with a custom comparator.

final queue = ZebaPriorityQueue<Task>(
  priority: (task) => task.priority,
  priorityComparator: (a, b) => b.compareTo(a),
);

Now lower numeric values have higher priority:

1  β†’ first
5  β†’ second
10 β†’ third

This is useful for systems where priority levels are represented as:

1 = Critical
2 = High
3 = Medium
4 = Low

πŸ₯ Example: Patient Queue

class Patient {
  const Patient({
    required this.name,
    required this.priority,
  });

  final String name;
  final int priority;
}

final patients = ZebaPriorityQueue<Patient>(
  priority: (patient) => patient.priority,
);

patients.enqueue(
  const Patient(
    name: 'Patient A',
    priority: 2,
  ),
);

patients.enqueue(
  const Patient(
    name: 'Patient B',
    priority: 10,
  ),
);

patients.enqueue(
  const Patient(
    name: 'Patient C',
    priority: 5,
  ),
);

Processing order:

Patient B β†’ 10
Patient C β†’ 5
Patient A β†’ 2

πŸ’Ό Example: Job Processing

class Job {
  const Job({
    required this.name,
    required this.priority,
  });

  final String name;
  final int priority;
}

final jobs = ZebaPriorityQueue<Job>(
  priority: (job) => job.priority,
);

jobs.enqueue(
  const Job(
    name: 'Generate report',
    priority: 3,
  ),
);

jobs.enqueue(
  const Job(
    name: 'Process payment',
    priority: 10,
  ),
);

jobs.enqueue(
  const Job(
    name: 'Send notification',
    priority: 5,
  ),
);

while (jobs.isNotEmpty) {
  final job = jobs.dequeue();

  print(job?.name);
}

Processing order:

Process payment
Send notification
Generate report

πŸ“š API Reference

ZebaPriorityQueue<T>

Creates a generic priority queue.

ZebaPriorityQueue<T>({
  required int Function(T item) priority,
  int Function(int a, int b) priorityComparator,
});

priority

Determines the numeric priority of an item.

priority: (item) => item.priority,

priorityComparator

Controls how priority values are compared.

Default behavior:

(a, b) => a.compareTo(b)

Higher values are processed first.

Reverse the ordering:

priorityComparator: (a, b) => b.compareTo(a),

enqueue()

Adds an item to the queue.

queue.enqueue(item);

dequeue()

Removes and returns the highest-priority item.

final item = queue.dequeue();

Returns null when the queue is empty.

peek()

Returns the highest-priority item without removing it.

final item = queue.peek();

Returns null when the queue is empty.

clear()

Removes every item from the queue.

queue.clear();

length

Returns the number of items.

queue.length

isEmpty

Returns true when the queue contains no items.

queue.isEmpty

isNotEmpty

Returns true when the queue contains one or more items.

queue.isNotEmpty

toList()

Returns the queue contents in their current priority order.

final items = queue.toList();

The returned list is unmodifiable.

⏱️ Complexity

The package uses an ordered list internally.

Operation Complexity
enqueue() O(n)
dequeue() O(n)
peek() O(1)
clear() O(1)
length O(1)
isEmpty O(1)
isNotEmpty O(1)
toList() O(n)

This implementation prioritizes a simple, predictable API and lightweight code.

πŸ§ͺ Testing

Run all tests:

flutter test

Run static analysis:

flutter analyze

Validate the package before publishing:

flutter pub publish --dry-run

The package includes tests covering:

  • Empty queues
  • Enqueue behavior
  • Priority ordering
  • Dequeue behavior
  • Peek behavior
  • Clear behavior
  • Length tracking
  • Custom comparators
  • Duplicate priorities
  • Duplicate items
  • Immutable toList() results
  • Adding items after dequeue

πŸ› οΈ Development

Clone the repository:

git clone https://github.com/zeba-academy/zeba_academy_priority_queue.git

Navigate to the project:

cd zeba_academy_priority_queue

Install dependencies:

flutter pub get

Run tests:

flutter test

Analyze:

flutter analyze

πŸ“ Project Structure

zeba_academy_priority_queue/
β”‚
β”œβ”€β”€ lib/
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   └── priority_queue.dart
β”‚   β”‚
β”‚   └── zeba_academy_priority_queue.dart
β”‚
β”œβ”€β”€ test/
β”‚   └── priority_queue_test.dart
β”‚
β”œβ”€β”€ analysis_options.yaml
β”œβ”€β”€ CHANGELOG.md
β”œβ”€β”€ LICENSE
β”œβ”€β”€ README.md
└── pubspec.yaml

🎯 Design Goals

This package is designed around a few simple principles:

  • Keep the API small.
  • Avoid unnecessary dependencies.
  • Support generic Dart types.
  • Make priority ordering customizable.
  • Keep queue state protected.
  • Provide predictable behavior.
  • Remain suitable for Flutter applications.
  • Keep the package easy to understand and maintain.

πŸ“Œ Use Cases

zeba_academy_priority_queue can be useful for:

  • Task scheduling
  • Job processing
  • Notification prioritization
  • Background work queues
  • Event processing
  • Patient prioritization
  • Request prioritization
  • Download queues
  • Game task systems
  • Message processing
  • Workflow systems
  • Data structure learning

🀝 Contributing

Contributions are welcome!

Before submitting a pull request:

  1. Fork the repository.
  2. Create a feature branch.
  3. Make your changes.
  4. Add or update tests.
  5. Run flutter test.
  6. Run flutter analyze.
  7. Update documentation when necessary.
  8. Submit a pull request.

Please keep contributions focused, documented, and tested.

πŸ› Issues and Feature Requests

If you find a bug or have an idea for an improvement, please open an issue in the project's GitHub repository.

When reporting a bug, include:

  • Dart version
  • Flutter version
  • Package version
  • Minimal reproduction
  • Expected behavior
  • Actual behavior

πŸ“„ License

This project is licensed under the GNU General Public License v3.0 (GPL-3.0).

You may use, study, modify, and redistribute this software under the terms of the GPL-3.0 license.

See the LICENSE file for the complete license text.

πŸ‘¨β€πŸ’» About Me

✨ I’m Sufyan bin Uzayr, an open-source developer passionate about building and sharing meaningful projects.

You can learn more about me and my work at sufyanism.com or connect with me on LinkedIn.

πŸŽ“ Your All-in-One Learning Hub!

πŸš€ Explore courses and resources in coding, tech, and development at zeba.academy and code.zeba.academy.

Empower yourself with practical skills through curated tutorials, real-world projects, and hands-on experience. Level up your tech game today! πŸ’»βœ¨

Zeba Academy is a learning platform dedicated to coding, technology, and development.

➑ Visit our main site: zeba.academy

➑ Explore hands-on courses and resources: code.zeba.academy

➑ Check out our YouTube for more tutorials: zeba.academy

➑ Follow us on Instagram: zeba.academy


Thank you for visiting! ❀️

Made with ❀️ by Zeba Academy.