Spacer Widget in Flutter – Simplest Flutter Widget
Spacer Widget in Flutter helps in creating empty spacer that can be used to tune the spacing between the Widgets by giving it a flex attribute!
Probably the simplest of all the Widgets in Flutter. Does not contain more than 1 attribute and has a very simple use case as well.
If you want to create a simple Spacer between Containers and not worry about how the container spaces will change when it scales to a bigger screen or smaller screen Spacer widget does it for you.
It can automatically calculate the available space between the widgets and uses the flex as the percentage of space between them. In this tutorial, we will see how the Spacer widget is created and can be used in the Flutter application.
But as always, use the below template to carry forward this tutorial.
Spacer Widget – Basics
To begin with, use the
Spacerclass to start creating empty spacers in your application. What Spacer does is at the base creates only empty white space between the widgets mentioned!
This is different from a Divider Widget as the divider widget can control the color size and lot more! Spacer’s sole purpose is to create empty white space between the mentioned Widgets! Could be a container widget, card widget, etc.
The Spacer contains only one attribute as mentioned below.
The flex attribute is used in order to specify the amount of white space needed. It takes in an Int as its value and can be used as given below.
Spacer( flex: 2)
The default value for Spacer’s flex attribute is 1. It can directly be called and Space will be created.
Note: Spacer widget is used primarily in Row Widget & Column Widget.
Spacer – Example App
The below code shows how the Spacer widget can be used to create the required empty space needed between 2 containers.
On running the application, you can find the difference between the flex:1 and flex:2 visibly. This way of organizing the empty space is the primary use of the Spacer().
This generates an app that looks like,
It is important to understand the difference between the Divider and Spacer in Flutter. You can also read about Divider Widget in Flutter article for better understanding of what is the key difference between these two widgets.
“Learn and Be Curious”