In Dart List are used as Array of items. In today's tutorial we will concat two different list into single list. There are 2 different ways to marge a List in dart. First is with List.addAll() method and other is with spread(...) three dot operator.
Flutter Dart Merge Two List
1. Marge List with addAll() method in Dart:
List.addAll() method will append all the other list elements at the end of current list. One more important thing is list in which we are merging should be growable.
Syntax:
void addAll(Iterable<String> iterable)
Code example:
void main() {
List<String> list1 = <String>['One', 'Two', 'Three'];
List<String> list2 = <String>['O', 'T', 'T'];
list1.addAll(list2);
print(list1);
}
Output:
Spread operator known as Tree Dotted Joint operator in programming languages. It is used to combine two list into new list.
Code example:
void main() {
List<String> list1 = <String>['One', 'Two', 'Three'];
List<String> list2 = <String>['O', 'T', 'T'];
List<String> list3 = [...list1, ...list2];
List<num> numList1 = [10.11, 9.22, 8.33];
List<num> numList2 = [7.01, 6, 5];
List<num> numList3 = [...numList1, ...numList2];
print(list3);
print(numList3);
}
Output:
Comments
Post a Comment