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)text
addAll()text
Iterable<T>text
TThe Error
dartfinal 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)
dartfinal 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
dartfinal numbers = <int>[1, 2, 3]; // add() for ONE element numbers.add(4); print(numbers); // [1, 2, 3, 4]
Method 3: Spread Operator
dartfinal 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()
dartfinal 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
| Method | Parameter | Use Case |
|---|---|---|
text | Single element text | Add one item |
text | text | Add many items |
text | Index + element | Add at position |
text | Index + iterable | Add many at position |
text | Spread | New combined list |
Summary
dartfinal 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:
is designed to add all elements from another iterable -- not a single element. UsetextaddAll()for one element,textadd()for multiple.textaddAll([items])