List<String> _fruits = ["apple", "banana"];
List<String> _vegetables = ["Potato", "carrot"];
_fruits.addAll(_vegetables); //This will join the list
print(_fruits)
Output
["apple", "banana", "Potato", "carrot"]
To concatenate or join two lists in dart or Flutter you can use .addAll() method. In the code snippet, we have defined two lists _fruits and _vegetables and we concatenate them.
If you do not want to merge the lists in the given list and want to create a new list that is the combination of two lists then you can use the below code.
Code Example
List companyList1 = ['Microsoft', 'Apple'];
List companyList2 = ['Devsheet', 'Tesla'];
// Create a new list by joining the above lists
List allCompanies = List.from(companyList1)..addAll(companyList2);
print(allCompanies);
Output
['Microsoft', 'Apple', 'Devsheet', 'Tesla']
You can also use the extend() function of Dart to join two or multiple lists. Here we pass all the lists variable to a list and use extend() method with it.
Code Example
List companyList1 = ['Microsoft', 'Apple'];
List companyList2 = ['Devsheet', 'Tesla'];
List companyList3 = ['SpaceX'];
var allCompanies = [companyList1, companyList2, companyList3].expand((i) => i).toList();
print(allCompanies);
Output
['Microsoft', 'Apple', 'Devsheet', 'Tesla', 'SpaceX']
In Dart, + operator also can be used to join two or multiple lists. You just need to place + operator between the lists and assign the result to a dart variable.
Syntax
List finalList = List1 + List2 + List3;
Code Example
List nameList1 = ['Rick', 'Carol'];
List nameList2 = ['Daryl', 'Negan'];
List nameList3 = ['Carl'];
List finalList = nameList1 + nameList2 + nameList3;
print(finalList);
Output
['Rick', 'Carol', 'Daryl', 'Negan', 'Carl']
You can use ... operator in dart or Flutter to join two or multiple lists. All you need to do is to place ... operator before the list variable name and pass them to a list.
Syntax
List finalList = [...List1, ...List2, ...List3]
Code Example
List nameList1 = ['Rick', 'Carol'];
List nameList2 = ['Daryl', 'Negan'];
List nameList3 = ['Carl'];
List finalList = [...nameList1, ...nameList2, ...nameList3];
print(finalList);
Output
['Rick', 'Carol', 'Daryl', 'Negan', 'Carl']
0 Comments