How to combine lists using the expand() method in Dart

Method

The expand() method in Dart can add all the elements of a list one by one to a new list. It is typically used to combine more than two lists.

Syntax

[list1, list2, list3].expand(x => x)

Note: Any variable name can be used in the place of x.

Return value

An iterable is returned.

Code

main() {
// Creating lists
List basket1 = ['Mango', 'Apple'];
List basket2 = ['Orange', 'Avocado', 'Grape'];
List basket3 = ['Lemon'];
// converting the lists to an iterable
var newBasketIterable = [basket1, basket2, basket3].expand((x) => x);
// combining the lists
var newBasket = newBasketIterable.toList();
// printing the iterable
print("Iterable: $newBasketIterable");
// printing the combined list
print("Combined List: $newBasket");
}

Explanation

  • Lines 4 to 6: We create three lists named basket1, basket2, and basket3.

  • Lines 9 to 11: We combine each item in the lists using the expand() method, and then pass the toList() method to convert to a list. The result is stored in a new list named newBasket.

  • Line 14: We print newBasketIterable, the iterable containing the elements of the three lists declared above.

  • Line 16: We print newBasket, the list containing the combined elements of the three lists declared above.

Free Resources