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.
[list1, list2, list3].expand(x => x)
Note: Any variable name can be used in the place of
x
.
An iterable is returned.
main() {// Creating listsList basket1 = ['Mango', 'Apple'];List basket2 = ['Orange', 'Avocado', 'Grape'];List basket3 = ['Lemon'];// converting the lists to an iterablevar newBasketIterable = [basket1, basket2, basket3].expand((x) => x);// combining the listsvar newBasket = newBasketIterable.toList();// printing the iterableprint("Iterable: $newBasketIterable");// printing the combined listprint("Combined List: $newBasket");}
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.