Skip to main content

What are Lists?

Lists in Dart are ordered collections of items. They are similar to arrays in other programming languages and can dynamically grow or shrink in size.

Creating Lists

You can create a list with a specific type using type annotations:
Lists in Dart can contain duplicate values, as shown in the example above where 20 appears twice.

Adding Elements

There are several methods to add elements to a list:

Adding a Single Element

Use the add() method to append an element to the end of the list:

Adding Multiple Elements

Use the addAll() method to append multiple elements at once:

Removing Elements

Dart provides multiple ways to remove elements from a list:

Remove by Value

The remove() method removes the first occurrence of a specific value:
The remove() method only removes the first occurrence of a value. If you need to remove all occurrences, you’ll need to call it multiple times or use a different approach.

Remove by Index

The removeAt() method removes an element at a specific position:

Accessing Elements

Access individual elements using bracket notation with the index (starting from 0):

List Properties

Dart lists provide several useful properties for querying information:

Searching in Lists

Check if Element Exists

Use contains() to check if a value exists:

Find Element Position

Use indexOf() to find the position of an element:
The indexOf() method returns -1 if the element is not found, making it useful for conditional checks.

Safe Element Removal

Combine indexOf() with conditional logic for safe removal:

Complete Example

Key Takeaways

Dynamic Size

Lists can grow and shrink dynamically using add(), addAll(), remove(), and removeAt()

Type Safe

Use type annotations like List<int> to ensure all elements are of the same type

Zero-Indexed

List indices start at 0, so the first element is at position 0

Rich API

Dart provides many built-in methods and properties for working with lists