Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
communitycreator

How to iterate over a queue in Dart

Maria Elijah

Overview

Dart allows users to manipulate data in the form of a queue. A queue is a collection of objects. When you want to create a first-in, first-out data collection, queues come in handy.

The forEach loop

The forEach loop is used to iterate over a queue.


When using a queue in a Dart program, you must import the dart: collection module.

Syntax


queue_name.forEach((value))

queue_name is the name of the queue.


Parameter and return

The forEach loop requires a value to perform its iteration and returns all values present in the queue.

Code

import 'dart:collection';

void main() {
  // Creating a Queue
  Queue<String> fruits = Queue<String>(); 

  // Adding elements to the queue
  fruits.add('Mango');
  fruits.add('Pawpaw');
  fruits.addFirst('Apple');
  fruits.addLast('Pineapple');
  
  // Printing each element using forEach
  fruits.forEach((value)=> print(value));
}

Explanation

  • In the code above, we import the dart:collection library to utilize the Queue class, then create a Queue named fruits.

  • Next, we use the methods add(), addFirst(), and addLast() to add elements to the queue.

    • The queue_name.add(element) method is used to add the element in the queue.

    • The queue_name.addFirst(element) method inserts the element from the front inside the queue.

    • The queue_name.addLast(element) method adds the element from back in the queue.

  • Finally, each element in the queue is printed out using the forEach loop.

RELATED TAGS

dart
communitycreator
RELATED COURSES

View all Courses

Keep Exploring