In Dart, a List is an ordered collection of items, similar to arrays in other languages. It allows you to store multiple values in a single variable and access them using an index. Lists in Dart can be fixed-length or growable, and they are zero-indexed, meaning the first element is at index 0.
For example, if I wanted to store a list of fruits and print them:
void main() {
List fruits = ['Apple', 'Banana', 'Mango']; // growable list
for (var fruit in fruits) {
print(fruit);
}
}
Here, fruits is a List of strings. Using a for-in loop, I can iterate through all items without worrying about indexes. Lists also have many useful methods like add(), remove(), insert(), length, contains(), and more.
In practical projects, I’ve used Lists extensively—for instance, storing user data fetched from an API and displaying it in a UI. One challenge I faced was when trying to modify a List while iterating over it; it led to unexpected behavior. To solve this, I either iterated over a copy of the List or used higher-order functions like forEach() or map().
A limitation of fixed-length Lists is that you cannot change their size after creation. In such cases, a growable List is a better alternative.
For example, adding a new item dynamically:
fruits.add('Orange');
print(fruits); // ['Apple', 'Banana', 'Mango', 'Orange']
Lists are very versatile and one of the most commonly used data structures in Dart for handling collections of data efficiently.
