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 theadd() method to append an element to the end of the list:
Adding Multiple Elements
Use theaddAll() method to append multiple elements at once:
Removing Elements
Dart provides multiple ways to remove elements from a list:Remove by Value
Theremove() method removes the first occurrence of a specific value:
Remove by Index
TheremoveAt() 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:| Property | Description | Example |
|---|---|---|
length | Returns the number of elements | numeros.length |
isEmpty | Returns true if the list is empty | numeros.isEmpty |
isNotEmpty | Returns true if the list has elements | numeros.isNotEmpty |
first | Returns the first element | numeros.first |
last | Returns the last element | numeros.last |
Searching in Lists
Check if Element Exists
Usecontains() to check if a value exists:
Find Element Position
UseindexOf() to find the position of an element:
Safe Element Removal
CombineindexOf() 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 typeZero-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