Dart/Flutter – How to combine lists

In this article, we go through several methods to combine/concatenate lists in Dart/Flutter.

final l1 = <int>[1, 2, 3];
final l2 = <int>[4, 5, 6];

1. Use operator +

void combineList_addOperator(l1, l2) {
  final combinedList = l1 + l2;
  print(combinedList);
}

2. Use Spread (…) operator

void combineList_spreadOperator(l1, l2) {
  final combinedList = [...l1, ...l2];
  print(combinedList);
}

3. Use addAll() method

void combineLists_addAll(l1, l2) {
  final combinedList = [];

  combinedList.addAll(l1);
  combinedList.addAll(l2);

  print(combinedList);
}

4. Use List.from() and addAll()

void combineList_from_addAll(l1, l2) {
  final combinedList = List.from(l1)..addAll(l2);
  print(combinedList);
}

5. Use List.of() and addAll()

void combineList_of_addAll(l1, l2) {
  final combinedList = List.of(l1)..addAll(l2);
  print(combinedList);
}

6. Use expand() method

void combineList_expand(l1, l2) {
  final combinedList = [l1, l2].expand((element) => element).toList();
  print(combinedList);
}

Output

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

If you are looking for mobile/web Software Engineers to build you next projects, please Drop us your request!

Tagged : / / / / /
Subscribe
Notify of
guest

1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Yo Ching Cha
2 years ago

nice

1
0
Would love your thoughts, please comment.x
()
x