How do I combine two lists in Dart?

Alex picture Alex · Feb 17, 2014 · Viewed 46.1k times · Source

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]

Answer

Alexandre Ardhuin picture Alexandre Ardhuin · Feb 17, 2014

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];