Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I combine two lists in Dart?

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]
like image 658
Alex Avatar asked Feb 17 '14 10:02

Alex


People also ask

How do you concatenate lists in flutter?

var list = [].. addAll(list1).. addAll(list2); Dart now supports the concatenation of lists using the + operator.

How do you make a nested list in darts?

A nested list is a list of lists or we can say the multidimensional list. Dart does not provide any native way to create a nested list. To create nested list we use the List. filled( ) or List.

How do you list an object by another list of items in Dart?

List<SomeClass> list = list to search; List<String> matchingList = list of strings that you want to match against; list. where((item) => matchingList. contains(item. relevantProperty));


Video Answer


3 Answers

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];
like image 106
Alexandre Ardhuin Avatar answered Oct 19 '22 09:10

Alexandre Ardhuin


maybe more consistent~

var list = []..addAll(list1)..addAll(list2);
like image 19
Ticore Shih Avatar answered Oct 19 '22 08:10

Ticore Shih


Dart now supports concatenation of lists using the + operator.

Example:

List<int> result = [0, 1, 2] + [3, 4, 5];
like image 16
Erlend Avatar answered Oct 19 '22 08:10

Erlend