Dart Lists
A List in Dart is an ordered collection of values. Each value is called an element, and its position is represented by a zero-based index. The first element is at index 0, the second is at index 1, and the last is at list.length - 1.
Dart does not provide a separate general-purpose array type. A List serves the same role as an array in many other programming languages.
A Dart List can be:
- Growable: elements can be added or removed.
- Fixed-length: existing elements can be replaced, but the number of elements cannot change.
- Unmodifiable: neither the length nor the elements can be changed through the unmodifiable list.
This tutorial explains how to create typed lists, access and update elements, work with fixed-length and growable lists, and use common List operations.
Dart List Syntax and Type Declaration
A List literal is written by placing comma-separated elements inside square brackets.
List<ElementType> listName = [element1, element2, element3];
The type argument inside <...> specifies which values the list can contain. For example, List<int> accepts integers and List<String> accepts strings.
void main() {
List<int> scores = [82, 91, 76];
List<String> cities = ['Delhi', 'Mumbai', 'Chennai'];
print(scores);
print(cities);
}
Output
[82, 91, 76]
[Delhi, Mumbai, Chennai]
Dart can also infer the element type from a list literal. For example, var numbers = [1, 2, 3]; is inferred as a List<int>.
Access Dart List Elements by Index
Use square brackets with an index to read an element. An index must be between 0 and list.length - 1.
void main() {
List<String> colors = ['red', 'green', 'blue'];
print(colors[0]);
print(colors[2]);
print(colors.first);
print(colors.last);
}
Output
red
blue
red
blue
Trying to access an index outside the valid range causes a RangeError.
Update an Element in a Dart List
Assign a new value to an index to replace the element at that position. This operation does not change the length of the list.
void main() {
List<String> fruits = ['apple', 'banana', 'orange'];
fruits[1] = 'mango';
print(fruits);
}
Output
[apple, mango, orange]
Dart Fixed-Length List
A fixed-length List has a defined number of positions. Its elements can normally be replaced, but operations such as add(), remove(), and clear() cannot change its length.
The following original example uses the older unnamed List constructor. That constructor belongs to legacy Dart code and is not supported in modern null-safe Dart. The modern replacement is shown immediately after it.
Legacy Fixed-Length Dart List Example
The following code demonstrates the syntax used by older Dart versions to create a List with three positions.
main.dart
void main(){
//define list with fixed length
var myList = new List(3);
//assign list with items
myList = [25, 63, 84];
print(myList);
}
In older Dart versions, the statement new List(3) created a List with three positions. The subsequent assignment replaces the variable with the growable List literal [25, 63, 84].
Output
[25, 63, 84]
Create a Fixed-Length List with List.filled()
In current Dart, use List.filled() with growable: false to create a fixed-length List.
void main() {
List<int> numbers = List<int>.filled(3, 0, growable: false);
numbers[0] = 25;
numbers[1] = 63;
numbers[2] = 84;
print(numbers);
}
Output
[25, 63, 84]
The value 3 is the List length, and 0 is the initial value assigned to every position. An operation such as numbers.add(96) throws an UnsupportedError because the List cannot grow.
Dart Growable List
A growable List can change its length while the program runs. List literals are growable by default unless they are made constant or wrapped in an unmodifiable List.
Common ways to create a growable List include:
- Assign a List literal containing initial elements.
- Create an empty typed List literal and add elements later.
- Use a constructor such as
List.empty(growable: true)orList.filled(..., growable: true).
Create a Growable List from a List Literal
In the following example, a growable List is created by assigning a List literal to a variable. The add() method appends another element.
main.dart
void main(){
var myList = [25, 63, 84];
print(myList);
//add item to growable list
myList.add(96);
print(myList);
}
Output
[25, 63, 84]
[25, 63, 84, 96]
Create an Empty Growable Dart List
The following example creates an empty growable List and then appends three values.
main.dart
void main() {
var myList = [];
myList.add(25);
myList.add(63);
myList.add(84);
print(myList);
}
Output
[25, 63, 84]
An untyped empty literal such as [] may be inferred as List<dynamic> when there is no surrounding type information. Prefer an explicit type when all elements should have the same type.
void main() {
List<int> numbers = [];
numbers.add(25);
numbers.addAll([63, 84]);
print(numbers);
}
Output
[25, 63, 84]
Add and Insert Elements in a Dart List
Use add() to append one element, addAll() to append multiple elements, and insert() to place an element at a specified index.
void main() {
List<String> tasks = ['Read'];
tasks.add('Write');
tasks.addAll(['Review', 'Submit']);
tasks.insert(1, 'Plan');
print(tasks);
}
Output
[Read, Plan, Write, Review, Submit]
Remove Elements from a Dart List
Dart provides methods for removing an element by value, index, range, or condition.
void main() {
List<int> numbers = [10, 20, 30, 40, 50];
numbers.remove(20);
numbers.removeAt(1);
numbers.removeWhere((number) => number > 40);
print(numbers);
}
Output
[10, 40]
remove(value) removes the first matching value and returns a Boolean indicating whether an element was removed. removeAt(index) removes and returns the element at the specified index.
Check Dart List Length and Contents
The length, isEmpty, and isNotEmpty properties describe the size of a List. The contains() method checks whether a value is present.
void main() {
List<String> languages = ['Dart', 'Java', 'Python'];
print(languages.length);
print(languages.isEmpty);
print(languages.isNotEmpty);
print(languages.contains('Dart'));
}
Output
3
false
true
true
Iterate Through a Dart List
A for-in loop is a direct way to process every element. Use an index-based loop when the position of each element is also required.
void main() {
List<String> names = ['Anu', 'Bala', 'Charan'];
for (String name in names) {
print(name);
}
for (int index = 0; index < names.length; index++) {
print('$index: ${names[index]}');
}
}
Output
Anu
Bala
Charan
0: Anu
1: Bala
2: Charan
Transform and Filter Dart List Elements
Use map() to transform each element and where() to retain elements that satisfy a condition. These methods return iterable values, so call toList() when a List result is needed.
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
List<int> squares = numbers.map((number) => number * number).toList();
List<int> evenNumbers = numbers.where((number) => number.isEven).toList();
print(squares);
print(evenNumbers);
}
Output
[1, 4, 9, 16, 25]
[2, 4]
Sort and Reverse a Dart List
The sort() method rearranges a mutable List in place. The reversed property provides an iterable view in reverse order.
void main() {
List<int> numbers = [40, 10, 30, 20];
numbers.sort();
List<int> descending = numbers.reversed.toList();
print(numbers);
print(descending);
}
Output
[10, 20, 30, 40]
[40, 30, 20, 10]
Create an Unmodifiable Dart List
Use List.unmodifiable() when callers should be able to read a List but not change it. Attempts to replace, add, or remove elements through the resulting List throw an UnsupportedError.
void main() {
List<String> roles = List<String>.unmodifiable([
'admin',
'editor',
'viewer',
]);
print(roles);
}
Output
[admin, editor, viewer]
Const Lists and Final List Variables in Dart
final and const affect Lists differently. A final variable cannot be assigned a different List after initialization, but the existing List may still be mutable. A const List is compile-time constant and cannot be modified.
void main() {
final List<int> mutableNumbers = [1, 2];
mutableNumbers.add(3);
const List<int> fixedValues = [10, 20, 30];
print(mutableNumbers);
print(fixedValues);
}
Output
[1, 2, 3]
[10, 20, 30]
Frequently Asked Questions About Dart Lists
Are Dart Lists the same as arrays?
A Dart List provides the indexed, ordered collection behavior commonly associated with arrays. Dart therefore uses Lists for most tasks that would use arrays in other languages.
What index does a Dart List start with?
A Dart List starts at index 0. A List containing three elements has the valid indexes 0, 1, and 2.
How do I create an empty typed List in Dart?
Declare the element type and assign an empty List literal, such as List<String> names = [];. This prevents values of unrelated types from being added.
How do I create a fixed-length List in modern Dart?
Use List.filled(length, initialValue, growable: false). You can replace values at valid indexes, but you cannot add or remove elements.
What is the difference between final and const Lists?
A final variable cannot refer to another List after initialization, although its current List may remain mutable. A const List cannot be modified.
Dart Lists Summary
In this Dart Tutorial, we learned how to create typed, fixed-length, growable, and unmodifiable Lists. We also accessed and updated elements by index and used common operations for adding, removing, iterating, filtering, transforming, sorting, and checking List contents.
TutorialKart.com