flutter
/

Dart List – The Ultimate Guide with Examples

Last Sync: Today

On this page

22
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

flutter

Dart List – The Ultimate Guide with Examples

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.

  1. List Literal

DARTRead-only
1
void main() {
  var fruits = ['Apple', 'Banana', 'Orange']; // inferred List<String>
  List<int> numbers = [1, 2, 3, 4, 5];        // explicit type
  print(fruits); // [Apple, Banana, Orange]
}

  1. Using List.filled()

Creates a list of a fixed length, filled with a specified value. The list cannot grow beyond its initial length.

DARTRead-only
1
void main() {
  var zeros = List.filled(5, 0);      // [0, 0, 0, 0, 0]
  var names = List.filled(3, '');     // ['', '', '']
  print(zeros);
}

  1. Using List.generate()

Creates a list by calling a generator function for each index.

DARTRead-only
1
void main() {
  var squares = List.generate(5, (index) => index * index);
  print(squares); // [0, 1, 4, 9, 16]
}

  1. From another collection (List.from() and List.of())

DARTRead-only
1
void main() {
  var original = [1, 2, 3];
  var copy1 = List.from(original);    // creates a new list
  var copy2 = List.of(original);       // also creates a new list
}

  1. Unmodifiable List

If you need a list that cannot be changed, use List.unmodifiable().

DARTRead-only
1
void main() {
  var fixed = List.unmodifiable([1, 2, 3]);
  // fixed.add(4); // Throws UnsupportedError
}

Accessing Elements

DARTRead-only
1
void main() {
  var colors = ['Red', 'Green', 'Blue'];
  print(colors[0]);      // Red
  print(colors.first);    // Red
  print(colors.last);     // Blue
  print(colors.length);   // 3
  
  // Check if an element exists
  print(colors.contains('Green')); // true
}

Adding Elements

DARTRead-only
1
void main() {
  var list = [1, 2];
  list.add(3);                // [1, 2, 3]
  list.addAll([4, 5]);        // [1, 2, 3, 4, 5]
  list.insert(2, 99);         // insert at index 2: [1, 2, 99, 3, 4, 5]
  list.insertAll(0, [10, 20]); // [10, 20, 1, 2, 99, 3, 4, 5]
}

Removing Elements

DARTRead-only
1
void main() {
  var list = [10, 20, 30, 20, 40];
  list.remove(20);           // removes first occurrence of 20 → [10, 30, 20, 40]
  list.removeAt(2);          // remove element at index 2 → [10, 30, 40]
  list.removeLast();         // remove last element → [10, 30]
  list.removeWhere((n) => n > 15); // remove all > 15 → [10]
  list.clear();              // []
}

Iterating Over a List

DARTRead-only
1
void main() {
  var fruits = ['Apple', 'Banana', 'Cherry'];
  
  // for loop with index
  for (int i = 0; i < fruits.length; i++) {
    print(fruits[i]);
  }
  
  // for-in loop
  for (var fruit in fruits) {
    print(fruit);
  }
  
  // forEach
  fruits.forEach((fruit) => print(fruit));
}

Common List Methods

Sorting

DARTRead-only
1
void main() {
  var numbers = [3, 1, 4, 1, 5];
  numbers.sort();           // ascending: [1, 1, 3, 4, 5]
  print(numbers);
  
  var names = ['Charlie', 'Alice', 'Bob'];
  names.sort();             // alphabetical: [Alice, Bob, Charlie]
  
  // Custom sort (descending)
  numbers.sort((a, b) => b.compareTo(a));
  print(numbers); // [5, 4, 3, 1, 1]
}

Reversing

DARTRead-only
1
void main() {
  var list = [1, 2, 3];
  var reversed = list.reversed.toList(); // [3, 2, 1]
}

Searching

DARTRead-only
1
void main() {
  var list = [10, 20, 30, 20];
  print(list.indexOf(20));     // 1
  print(list.lastIndexOf(20)); // 3
  print(list.contains(30));    // true
}

Filtering and Transforming

DARTRead-only
1
void main() {
  var numbers = [1, 2, 3, 4, 5];
  
  // where (filter)
  var even = numbers.where((n) => n % 2 == 0).toList(); // [2, 4]
  
  // map (transform)
  var squared = numbers.map((n) => n * n).toList(); // [1, 4, 9, 16, 25]
  
  // any / every
  print(numbers.any((n) => n > 4));   // true
  print(numbers.every((n) => n > 0)); // true
}

Reducing and Folding

DARTRead-only
1
void main() {
  var numbers = [1, 2, 3, 4];
  var sum = numbers.reduce((a, b) => a + b);   // 10
  var product = numbers.fold(1, (a, b) => a * b); // 24
}

Combining Lists

DARTRead-only
1
void main() {
  var list1 = [1, 2];
  var list2 = [3, 4];
  var combined = [...list1, ...list2]; // spread operator
  print(combined); // [1, 2, 3, 4]
  
  // Using + operator
  var alsoCombined = list1 + list2; // [1, 2, 3, 4]
}

Collection If and For

Dart allows using if and for inside collection literals, which is very handy for conditional or computed elements.

DARTRead-only
1
void main() {
  bool addExtra = true;
  var numbers = [1, 2, if (addExtra) 3, 4]; // [1, 2, 3, 4]
  
  var doubled = [for (var n in [1, 2, 3]) n * 2]; // [2, 4, 6]
}

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

DARTRead-only
1
void main() {
  // Create a list of numbers
  var scores = [85, 92, 78, 90, 88];
  
  // Add a new score
  scores.add(95);
  
  // Calculate average
  double sum = scores.reduce((a, b) => a + b).toDouble();
  double average = sum / scores.length;
  print('Average: $average');
  
  // Filter passing scores (> 80)
  var passing = scores.where((s) => s > 80).toList();
  print('Passing scores: $passing');
  
  // Sort in descending order
  scores.sort((a, b) => b.compareTo(a));
  print('Sorted descending: $scores');
  
  // Check if any score is perfect
  if (scores.contains(100)) {
    print('Perfect score!');
  } else {
    print('No perfect score.');
  }
}

Key Takeaways

    • Lists are ordered, zero‑based collections.
    • Use literals [], List.filled, List.generate, or List.from to create lists.
    • Add elements with add, addAll, insert, insertAll.
    • Remove elements with remove, removeAt, removeLast, removeWhere, clear.
    • Iterate with for, for-in, or forEach.
    • Transform lists using map, where, reduce, fold.
    • Use spread operator ... and collection if/for for concise construction.
    • Many useful methods: sort, reversed, indexOf, contains, etc.

Try it yourself

void main() {
  // Create a list
  var fruits = ['Apple', 'Banana', 'Mango'];
  
  // Add a fruit
  fruits.add('Orange');
  
  // Print all fruits
  fruits.forEach(print);
  
  // Check if 'Banana' exists
  print('Contains Banana? ${fruits.contains('Banana')}');
}

Test Your Knowledge

Q1
of 4

What is the output of this code? void main() { var list = [1, 2, 3]; list.add(4); print(list.length); }

A
3
B
4
C
5
D
Error
Q2
of 4

How do you create a list with 5 elements all equal to 0?

A
List(5, 0)
B
List.filled(5, 0)
C
List.generate(5, 0)
D
[0]*5
Q3
of 4

Which method removes the last element of a list?

A
removeLast()
B
pop()
C
deleteLast()
D
remove()
Q4
of 4

What does the spread operator `...` do?

A
Combines two lists into one
B
Creates a range of numbers
C
Expands an iterable into individual elements inside another collection
D
Duplicates the list

Previous

dart null safety

Next

dart set

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.