33 Spead Operator
The ...
syntax in Dart is called the spread operator. It “spreads” or expands the elements of an iterable (like a List) into individual elements.
In your code example:
...findings.map((finding) => _buildFindingRow(finding))
Here’s what’s happening step by step:
findings.map((finding) => _buildFindingRow(finding))
returns anIterable<Widget>
- The
...
operator takes each Widget from that iterable and spreads them as separate elements - This is commonly used when building lists of widgets in Flutter
33.1 Visual Representation
Without spread operator:
[
someWidget,
[widget1, widget2, widget3], // This creates a nested list
anotherWidget
]
With spread operator:
[
someWidget,
...findings.map(...) // This expands to: widget1, widget2, widget3
anotherWidget
]
Final result:
[
someWidget,
widget1,
widget2,
widget3,
anotherWidget
]
33.2 Practical Example
// Sample data
List<String> findings = ['Normal heart', 'Clear lungs', 'No fractures'];
// Without spread operator (creates nested structure)
List<Widget> badExample = [
'Report:'),
Text(.map((finding) => Text(finding)).toList(), // This is a List<Widget> inside the main list
findings'End of report')
Text(
];
// With spread operator (flattens the structure)
List<Widget> goodExample = [
'Report:'),
Text(...findings.map((finding) => Text(finding)), // Each Text widget becomes a separate element
'End of report')
Text( ];
The spread operator is particularly useful in Flutter when you need to conditionally include widgets or when mapping over data to create multiple widgets in a Column, Row, or ListView.