What is a List in Dart?
A List is an ordered collection of objects. It's one of the most commonly used data structures in Dart. Lists are zero‑based (the first element has index 0), and they can grow or shrink dynamically. Lists can contain duplicate elements and can be of any type, including mixed types if you use a non‑specific type like List<dynamic>.
Creating Lists
Dart offers multiple ways to create lists, depending on your needs.
- List Literal
- Using
List.filled()
List.filled()Creates a list of a fixed length, filled with a specified value. The list cannot grow beyond its initial length.
- Using
List.generate()
List.generate()Creates a list by calling a generator function for each index.
- From another collection (
List.from() and List.of())
List.from() and List.of())
- Unmodifiable List
If you need a list that cannot be changed, use List.unmodifiable().
Accessing Elements
Adding Elements
Removing Elements
Iterating Over a List
Common List Methods
Sorting
Reversing
Searching
Filtering and Transforming
Reducing and Folding
Combining Lists
Collection If and For
Dart allows using if and for inside collection literals, which is very handy for conditional or computed elements.
List Properties
length– number of elements.
isEmpty– true if the list has no elements.
isNotEmpty– true if the list has at least one element.
first– first element (throws if empty).
last– last element (throws if empty).
reversed– an iterable of the list in reverse order.
Complete Example
Key Takeaways
- Lists are ordered, zero‑based collections.
- Use literals
[],List.filled,List.generate, orList.fromto create lists.
- Use literals
- Add elements with
add,addAll,insert,insertAll.
- Add elements with
- Remove elements with
remove,removeAt,removeLast,removeWhere,clear.
- Remove elements with
- Iterate with
for,for-in, orforEach.
- Iterate with
- Transform lists using
map,where,reduce,fold.
- Transform lists using
- Use spread operator
...and collectionif/forfor concise construction.
- Use spread operator
- Many useful methods:
sort,reversed,indexOf,contains, etc.
- Many useful methods: