Merging 2 lists in Dart

Last updated on January 28, 2022 Hadrianus Loading... Post a comment

This article shows you a couple of different ways to join 2 lists in Dart.

Using Addition (+) Operator

Example:

void main() {
  final List list1 = [1, 2, 3];
  final List list2 = [4, 5, 6];
  final List list3 = list1 + list2;
  print(list3);
}

Output:

[1, 2, 3, 4, 5, 6]

Using List addAll() method

The List class of Dart provides the addAll method that helps you easily join 2 lists together.

Example:

void main() {
  List listA = [1, 2, 3];
  List listB = [4, 5, 6];
  listA.addAll(listB);
  print(listA);
  
  List<String> listC = ['Dog', 'Cat'];
  List<String> listD = ['Bear', 'Tiger'];
  listC.addAll(listD);
  print(listC);
}

Output:

[1, 2, 3, 4, 5, 6]
[Dog, Cat, Bear, Tiger]

You can find more information about the addAll() method in the official docs.

Using Spread Operator

Example:

void main() {
  final List list1 = ['A', 'B', 'C'];
  final List list2 = ['D', 'E', 'F'];
  final List list3 = [...list1, ...list2];
  print(list3);
}

Output:

[A, B, C, D, E, F]

You can find more details about the spread operator syntax in the Dart language tour.

Wrapping Up

We’ve walked through a few approaches to combining lists in Dart. This knowledge is very helpful when working with data-driven applications. If you’d like to explore more about Dart and Flutter, take a look at the following articles:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles