I was wondering if there was an easy way to concatenate two lists in dart to create a brand new list object. I couldn\'t find anything and something like this:
My list:
Dart now supports concatenation of lists using the +
operator.
Example:
List<int> result = [0, 1, 2] + [3, 4, 5];
If you want to merge two lists and remove duplicates could do:
var newList = [...list1, ...list2].toSet().toList();
We can add all the elements of the other list to the existing list by the use of addAll()
method.
Using addAll()
method to add all the elements of another list to the existing list. and Appends all objects of iterable to the end of this list.
Extends the length of the list by the number of objects in iterable. Throws an UnsupportedError
if this list is fixed-length.
Creating lists
listone = [1,2,3]
listtwo = [4,5,6]
Combining lists
listone.addAll(listtwo);
Output:
[1,2,3,4,5,6]
maybe more consistent~
var list = []..addAll(list1)..addAll(list2);
addAll
is the most common way to merge two lists.
But to concatenate list of lists, you can use any of these three functions (examples below):
void main() {
List<int> a = [1,2,3];
List<int> b = [4,5];
List<int> c = [6];
List<List<int>> abc = [a,b,c]; // list of lists: [ [1,2,3], [4,5], [6] ]
List<int> ints = abc.expand((x) => x).toList();
List<int> ints2 = abc.reduce((list1,list2) => list1 + list2);
List<int> ints3 = abc.fold([], (prev, curr) => prev + curr); // initial value is []
print(ints); // [1,2,3,4,5,6]
print(ints2); // [1,2,3,4,5,6]
print(ints3); // [1,2,3,4,5,6]
}
You can use:
var newList = new List.from(list1)..addAll(list2);
If you have several lists you can use:
var newList = [list1, list2, list3].expand((x) => x).toList()
As of Dart 2 you can now use +
:
var newList = list1 + list2 + list3;
As of Dart 2.3 you can use the spread operator:
var newList = [...list1, ...list2, ...list3];