Flutter Tip! Use Spread Operator!

Flutter Queen✨
2 min readMay 23, 2023

In Flutter, the spread operator (...) is used to "spread" the elements of an iterable (such as a list or set) into another collection or as arguments to a function. It allows you to easily combine or extract values from collections without explicitly iterating over them.

With the use of Spread Operator, you can enhance code efficiency, improve readability, and maintain code more effectively. It offers a concise and flexible approach to handle complex data structures, making your code more expressive and concise.

Example 1: Combining Lists

void main() {
List<int> list1 = [1, 2, 3];
List<int> list2 = [4, 5, 6];

List<int> combinedList = [...list1, ...list2];
print(combinedList); // Output: [1, 2, 3, 4, 5, 6]
}

Example 2: Use of Spread Operator in Flutter Widgets:

bool isLoading = false;

Widget build(BuildContext context) {
return Column(
children: [
if (isLoading) ...[
Text('Loading...'),
Text('Loading...'),
Text('Loading...'),
Text('Loading...'),
],
Text('Other widget'),
],
);
}

Example 3: Use of Spread Operator in more complex way:

bool isLoading = false;
List<int> numbers = [1, 2, 3, 4, 5];
String title = 'Data List';

Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Column(
children: [
if (isLoading) ...[
CircularProgressIndicator(),
SizedBox(height: 16.0),
],
...numbers.map((number) => ListTile(
title: Text('Number $number'),
)),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
isLoading = !isLoading;
});
},
child: Icon(Icons.refresh),
),
);
}

Conclusion:

the spread operator in Flutter is a powerful tool that simplifies working with collections by spreading iterable elements into other collections or as function arguments. By leveraging the spread operator, you can combine, extract, and manipulate values from lists, sets, and maps with ease.

I hope this article was helpful to you. Thank you for taking the time to read it. Your feedback and suggestions are always welcome.

Support Me:

--

--