Spacing strategy
- Flutter course
- Beginner
- Lesson 39/99
- 4 min
Learn how to choose between padding and margin.
When padding, when margin?
The choice between padding and margin depends on where the spacing belongs. If the space is part of the widget's own visual area (e.g. between the background color and the child), use padding. If the space is between the widget and neighboring widgets (distance between widgets), use margin.
// Distance from text to edge inside a card -> padding
Container(
color: Colors.blue,
padding: EdgeInsets.all(16),
child: Text('İç boşluk'),
)
// Distance between two cards -> margin
Container(
margin: EdgeInsets.only(bottom: 12),
child: Text('Kart 1'),
)
Container(
child: Text('Kart 2'),
)Building a layout
A good layout comes from conscious use of padding and margin. Use margin for distance between list items, padding for space between text and edge inside a card. For equal distance between children in a Column or Row, mainAxisAlignment: spaceBetween is also an option; it is an alternative to giving each child a margin individually.
Column(
children: [
Container(
margin: EdgeInsets.only(bottom: 8),
child: Text('Öğe 1'),
),
Container(
margin: EdgeInsets.only(bottom: 8),
child: Text('Öğe 2'),
),
// or mainAxisAlignment: spaceBetween
],
)Practice Print strategy info
In main, print two lines with print: ic bosluk padding and dis bosluk margin.
Starter code
void main() {
// iki satır yazdır:
// ic bosluk padding
// dis bosluk margin
}Sample solution
void main() {
print('ic bosluk padding');
print('dis bosluk margin');
}Expected output
ic bosluk padding dis bosluk margin
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is used to put space between a widget's background and its text?
- padding Correct answer
- alignment
- decoration
- margin
Explanation: The space between background and text belongs to the widget's own area, so padding is used.
2 Space to a specific side
Container(
margin: EdgeInsets.____(bottom: 12),
child: Text('Kart'),
)
Container(
margin: EdgeInsets.only(bottom: 12),
child: Text('Kart'),
)
Explanation: The only constructor gives values only to specified sides.
3 Spacing strategy concepts
| Term | Meaning |
|---|---|
iç boşluk |
Between background and child |
dış boşluk |
Between neighboring widgets |
layout |
Arrangement of widgets |
mainAxisAlignment.spaceBetween |
Automatic distance between children |