fixed_queue

A simple Dart package that provides a FixedQueue, a queue with a fixed maximum size. When the queue is full and a new element is added, the oldest element is discarded.

This data structure is useful for scenarios like maintaining a history of recent events, caching, or managing a buffer of a constant size.

Features

  • Fixed Size: Enforces a maximum number of elements.
  • FIFO on Overflow: When a new item is added to a full queue, the first (oldest) item is removed.
  • Iterable: Implements Iterable<T>, allowing you to use for-in loops, toList(), etc.
  • Indexed Access: Provides [] operator for direct access to elements by index.

Getting started

Add fixed_queue to your pubspec.yaml dependencies:

dependencies:
  fixed_queue: ^1.0.0

Then, run dart pub get or flutter pub get.

Usage

Import the package and create an instance of FixedQueue.

import 'package:fixed_queue/fixed_queue.dart';

void main() {
  // Create a queue with a maximum size of 2.
  final queue = FixedQueue<String>(maxSize: 2);

  // The queue is initially empty.
  print('Length: ${queue.length}'); // Output: Length: 0

  // Add some elements.
  queue.push("a");
  queue.push("b");

  // The queue is now full.
  print('Queue: ${queue.toList()}'); // Output: Queue: [a, b]
  print('Length: ${queue.length}'); // Output: Length: 2

  // Add another element. "a" (the oldest element) will be removed.
  queue.push("c");

  print('Queue after overflow: ${queue.toList()}'); // Output: Queue after overflow: [b, c]
  print('Length: ${queue.length}'); // Output: Length: 2

  // You can access elements by index.
  print('Element at index 0: ${queue[0]}'); // Output: Element at index 0: b
  print('Element at index 1: ${queue[1]}'); // Output: Element at index 1: c
}

Libraries

fixed_queue