How do I combine two lists in Dart?
95,914
Solution 1
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];
Solution 2
maybe more consistent~
var list = []..addAll(list1)..addAll(list2);
Solution 3
Dart now supports concatenation of lists using the +
operator.
Example:
List<int> result = [0, 1, 2] + [3, 4, 5];
Solution 4
If you want to merge two lists and remove duplicates could do:
var newList = [...list1, ...list2].toSet().toList();
Solution 5
Alexandres' answer is the best but if you wanted to use + like in your example you can use Darts operator overloading:
class MyList<T>{
List<T> _internal = new List<T>();
operator +(other) => new List<T>.from(_internal)..addAll(other);
noSuchMethod(inv){
//pass all calls to _internal
}
}
Then:
var newMyList = myList1 + myList2;
Is valid :)
Author by
Alex
Updated on July 08, 2022Comments
-
Alex almost 2 years
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:
list1 = [1, 2, 3] list2 = [4, 5, 6]
I tried:
var newList = list1 + list2;
I wanted the combined output of:
[1, 2, 3, 4, 5, 6]
-
Florian Loitsch about 10 yearsAn alternative (which allows to easily concatenate many lists):
[list1, list2, list3, ...].expand((x) => x).toList()
; -
Abbas.M almost 5 yearsOld i know but what is the
..addAll()
why not just a single dot? -
csga5000 over 4 years@Abbas.M .. is for chaining, to do with out the double dot you would have to: list = []; list.addAll(list1); list.addAll(list2); The way I see it, it basically means call this function, but ignore what it returns, and keep operating on the object we were operating on.
-
Sébastien almost 4 yearsNote that the
+
operator cannot be be used on lists of different types. (in this case you get an error liketype 'List<Widget>' is not a subtype of type 'List<Image>'
. ). The spread operator works great for this use case though. -
Roxx almost 4 yearsCan you please check this question and suggest me something. stackoverflow.com/questions/62228799/…
-
Fuad All almost 4 yearsbest solution with preventing duplicate items.👍
-
visoft over 2 yearsTrue, listone will contain the sum. But addAll will return null. Can't use it where you want the result, directly (like list of widgets)
-
PJP over 2 yearsIt helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code.
-
Sassan about 2 years
var newList = {...list1, ...list2}.toList();