Dart List addAll()
Syntax & Examples
Syntax of List.addAll()
The syntax of List.addAll() method is:
void addAll(Iterable<E> iterable)
This addAll() method of List appends all objects of iterable
to the end of this list.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
iterable | required | the iterable whose elements will be added to the list |
Return Type
List.addAll() returns value of type void
.
✐ Examples
1 Combine two lists of numbers
In this example,
- We create a list named
numbers
containing the integers1, 2, 3
. - We create another list named
additionalNumbers
containing the integers4, 5, 6
. - We use the
addAll()
method to append all elements fromadditionalNumbers
to the end ofnumbers
. - The combined list is printed to standard output.
Dart Program
void main() {
List<int> numbers = [1, 2, 3];
List<int> additionalNumbers = [4, 5, 6];
numbers.addAll(additionalNumbers);
print('Combined list: $numbers'); // Output: Combined list: [1, 2, 3, 4, 5, 6]
}
Output
Combined list: [1, 2, 3, 4, 5, 6]
2 Combine two lists of characters
In this example,
- We create a list named
characters
containing the characters'a', 'b'
. - We create another list named
additionalCharacters
containing the characters'c', 'd'
. - We use the
addAll()
method to append all elements fromadditionalCharacters
to the end ofcharacters
. - The combined list is printed to standard output.
Dart Program
void main() {
List<String> characters = ['a', 'b'];
List<String> additionalCharacters = ['c', 'd'];
characters.addAll(additionalCharacters);
print('Combined list: $characters'); // Output: Combined list: [a, b, c, d]
}
Output
Combined list: [a, b, c, d]
3 Combine two lists of strings
In this example,
- We create a list named
fruits
containing the string'apple'
. - We create another list named
additionalFruits
containing the strings'banana', 'cherry'
. - We use the
addAll()
method to append all elements fromadditionalFruits
to the end offruits
. - The combined list is printed to standard output.
Dart Program
void main() {
List<String> fruits = ['apple'];
List<String> additionalFruits = ['banana', 'cherry'];
fruits.addAll(additionalFruits);
print('Combined list: $fruits'); // Output: Combined list: [apple, banana, cherry]
}
Output
Combined list: [apple, banana, cherry]
Summary
In this Dart tutorial, we learned about addAll() method of List: the syntax and few working examples with output and detailed explanation for each example.