Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn Dart Collections

In Dart, collections are objects used to store multiple values in an organized and iterable manner. Dart provides built-in support for various types of collections, including lists, sets, maps, and queues. These collection types offer different characteristics and are suited for different use cases.


Lists

Ordered collection of elements.
Allows duplicate elements.
Accessed by index.

List< int> numbers = [1, 2, 3, 4, 5];
List< String> names = ['Alice', 'Bob', 'Charlie'];


Set

Unordered collection of unique elements.
Does not allow duplicate elements.
Efficient for membership tests.

Set< int> uniqueNumbers = {1, 2, 3, 4, 5};
Set< String> uniqueNames = {'Alice', 'Bob', 'Charlie'};


Map

Collection of key-value pairs.
Keys must be unique.
Accessed by key.

Map ages = {'Alice': 30, 'Bob': 25, 'Charlie': 35};
Map students = {1: 'Alice', 2: 'Bob', 3: 'Charlie'};

Queue:

Ordered collection supporting efficient insertion and removal operations at both ends.
Useful for implementing FIFO (First-In-First-Out) data structures.

import 'dart:collection';
Queue queue = Queue();
queue.addAll([1, 2, 3]);
queue.removeFirst();
queue.removeLast();

Common Operations on Collections:

Adding Elements:
Lists: list.add(value), list.addAll(otherList).
Sets: set.add(value).
Maps: map[key] = value


Removing Elements
Lists: list.remove(value), list.removeAt(index).
Sets: set.remove(value).
Maps: map.remove(key).


Iterating :
Using for-in loops or methods like forEach().

List< int > numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => print(number));
Set< String > names = {'Alice', 'Bob', 'Charlie'};
for (var name in names) {
print(name);
}
Map< String, int > ages = {'Alice': 30, 'Bob': 25, 'Charlie': 35};
ages.forEach((key, value) => print('$key is $value years old'));



Immutable Collections:
Dart also provides immutable versions of collections using the const keyword, which prevents modifications after initialization.

var constantList = const [1, 2, 3];
var constantSet = const {'Alice', 'Bob', 'Charlie'};
var constantMap = const {'Alice': 30, 'Bob': 25, 'Charlie': 35};






Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java