Flutter reduce line of code using Spread (…)

tekeshwar singh
2 min readMay 26, 2021
Photo by Martin Shreder on Unsplash

The spread operator is a useful and quick syntax for adding items to arrays, and combining arrays.

But today we will learn how we can use the spread operator (…) in UI Code to reduce lines of code.

  1. Basic Approach
Basic Approach

As you can see in the above code we have a column containing a Button and 5 little.

Now our task is to reduce this repeating lines.

2. Nested Column (General Approach)

Generally, we have encountered something like this we use a Column inside the Column and pass a List to its children.

It’s Good but what we can go from 90% to 100%.

Nested Column

3. Spread (…) Approach

The spread operator is simple to use just add … is the beginning and you are good to go.

But you may think why it’s not throwing an error. That’s simple as Column Contains a List<Widget> and spread operator can be used to add an existing List in another List it accepts and understands.

Using Spread Operator

4. More using Spread

You will be thinking what’s the point of going from 90% to 100% as few new developers can get confused with this syntax.

So, let’s check the below example where I am using an if condition inside a Column with spread which conditionally renders widgets and it’s better than using a Nested Columns with Ternary Operator.

Spread Operator with If Condition

That’s it for this article but there is no limitation to using this teeny-tiny operator in numerous places.

--

--