Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
dart

How to combine lists using the spread operator in Dart

Maria Elijah

Overview

The spread operator is shown by three dots ... followed by the list’s name. The spread operator now combines lists in Dart, thanks to the Dart 2.3 upgrade.

The spread operator combines two or more list instances. It also extends a collection’s elements of a such as a list.

Syntax

The syntax of the Spread operator is given below:

...(List_name),...(List_name2);

Code

main() {
    
  // Creating lists
  List list1 = ['Mango', 'Apple'];
  List list2 = ['Orange', 'Avocado', 'Grape'];
  List list3 = ['Lemon'];
    
  // Combining lists
  var combinedList = [...list1, ...list2, ...list3];
    
  // Printing combined list
  print(combinedList);

  // extending newList using spread operator
  List newList = ['One',...list1];
  // display result
  print(newList);

}

Code explanation

Line 3-6: We create three lists named list1, list2, and list3.

Line 9: We combine the lists using the spread operator (...). This is then stored in the combinedList variable.

Line 12: We display the combined list.

Line 15: We extend newList with the elements in list1 using the spread operator.

RELATED TAGS

communitycreator
dart
RELATED COURSES

View all Courses

Keep Exploring