Dart – Join Two Lists

You can join two Lists in Dart in many ways. In this tutorial, we will go through two methods to join lists.

The first one is using List.addAll(). Pass the list as argument, to addAll() method, which you would like to append to this list.

The second way is traversing through the second list and adding the element during iteration to the first list.

Join Lists in Dart using List.addAll()

In this example, we take two lists list1 and list2. And then use addAll() to append list2 to list1.

List.addAll() modifies this list. So list1 gets modified, i.e., elements of list2 get appended to list1.

Dart Program

void main(){
	List list1 = [24, 'Hello', 84];
	List list2 = [41, 65];
	
	//join list2 to list1
	list1.addAll(list2);
	
	print(list1);
}

Output

[24, Hello, 84, 41, 65]
ADVERTISEMENT

Add Elements of other list one by one to first list

This is a primitive way of joining two lists. Here, we traverse through each element of list2 using forEach and add these elements to list1.

Dart Program

void main(){
	List list1 = [24, 'Hello', 84];
	List list2 = [41, 65];
	
	//join list2 to list1
	list2.forEach((element) => list1.add(element));
	
	print(list1);
}

Output

[24, Hello, 84, 41, 65]

Conclusion

In this Dart Tutorial, we learned how to append or join a list to another using List.addAll() and List.add() methods.