In Dart programming, the List data type is similar to arrays in other programming languages. A list is used to represent a collection of objects. It is an ordered group of objects. The core libraries in Dart are responsible for the existence of List class, its creation, and manipulation. These are some ways to combine two or more list:
Using addAll() method to add all the elements of other lists to the existing list
We can add all the elements of the other list to the existing list by the use of addAll() method.
// Main function
main() {
// Creating lists
List g1 = [‘dog’,’cat’];
List g2 = [‘Goat’];
// Combining lists
g1.addAll(g2);
// Printing combined list
print(g1);
}
Output:
[dog, cat, Goat]
Using + operator to combine list
We can also add lists together by the use of + operator in Dart.
// Main function
main() {
// Creating lists
List g1 = [‘Welcome’];
List g2 = [‘to’];
List g3 = [‘J&J’];
// Combining lists
var newgList = g1 + g2 + g3;
// Printing combined list
print(newgList);
}
Output:
[Welcome, to, J&J]
Using spread operator to combine the list
As of Dart 2.3 update, one can also use the spread operator to combine the list in Dart.
// Main function
main() {
// Creating lists
List g1 = [‘Welcome’];
List g2 = [‘to’];
List g3 = [‘J&J’];
// Combining lists
var newgList = […g1, …g2, …g3];
// Printing combined list
print(newgList);
}
Output:
[Welcome, to, J&J]