Question #175MediumDart Basics

Why does `numbers.addAll(2)` throw a compilation error in Dart, and how do you correctly add multiple items to a List?

#dart

Answer

Overview

text
numbers.addAll(2)
throws a compilation error because
text
addAll()
expects an
text
Iterable<T>
(a collection), not a single value
text
T
. You need to pass a list or other iterable.


The Error

dart
final numbers = <int>[1, 2, 3];

// Compilation error
numbers.addAll(2);
// Error: The argument type 'int' can't be assigned to the parameter type 'Iterable<int>'

// The signature is:
// void addAll(Iterable<E> iterable)
// It expects a List, Set, Iterable -- not a single element!

Correct Ways to Add Multiple Items

Method 1: addAll() with a List (Iterable)

dart
final numbers = <int>[1, 2, 3];

// Pass a list (Iterable)
numbers.addAll([4, 5, 6]);
print(numbers); // [1, 2, 3, 4, 5, 6]

numbers.addAll({7, 8});        // Set is also Iterable
numbers.addAll({9: true}.keys); // Keys iterable

Method 2: add() for a Single Element

dart
final numbers = <int>[1, 2, 3];

// add() for ONE element
numbers.add(4);
print(numbers); // [1, 2, 3, 4]

Method 3: Spread Operator

dart
final original = [1, 2, 3];
final extras = [4, 5, 6];

// Create new list with spread
final combined = [...original, ...extras];
print(combined); // [1, 2, 3, 4, 5, 6]

Method 4: insert() / insertAll()

dart
final list = [1, 2, 3];

list.insert(1, 99);            // Insert 99 at index 1
list.insertAll(0, [0, -1]);    // Insert multiple at index 0
print(list); // [0, -1, 1, 99, 2, 3]

Full Method Reference

MethodParameterUse Case
text
add(element)
Single element
text
E
Add one item
text
addAll(iterable)
text
Iterable<E>
Add many items
text
insert(index, element)
Index + elementAdd at position
text
insertAll(index, iterable)
Index + iterableAdd many at position
text
[...list1, ...list2]
SpreadNew combined list

Summary

dart
final list = <int>[1, 2, 3];

// Wrong -- single int, not iterable
// list.addAll(4);

// Correct options:
list.add(4);           // Add single element
list.addAll([4, 5]);   // Add multiple via list
final merged = [...list, 4, 5]; // New list via spread

Root cause:

text
addAll()
is designed to add all elements from another iterable -- not a single element. Use
text
add()
for one element,
text
addAll([items])
for multiple.