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 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");}
Explanation
-
Lines 4 to 6: We create three lists named
basket1,basket2, andbasket3. -
Lines 9 to 11: We combine each item in the lists using the
expand()method, and then pass thetoList()method to convert to a list. The result is stored in a new list namednewBasket. -
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.