How to Add Spacing in Flutter: Simple Methods Explained
In Flutter, you add spacing between widgets using
SizedBox for fixed space, Padding for inner spacing, and Spacer to fill flexible space in layouts. These widgets help control the distance and alignment of UI elements easily.Syntax
Here are common widgets to add spacing in Flutter:
- SizedBox: Adds fixed width or height space.
- Padding: Adds space inside a widget's boundary.
- Spacer: Expands to fill available space in a flex container.
dart
SizedBox(width: 20.0, height: 10.0); Padding(padding: EdgeInsets.all(8.0), child: Widget()); Spacer(flex: 1);
Example
This example shows how to add horizontal and vertical spacing between text widgets using SizedBox and Padding. It also uses Spacer to push widgets apart inside a row.
dart
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Spacing Example')), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ const Text('Above SizedBox'), const SizedBox(height: 20), const Text('Below SizedBox'), Padding( padding: const EdgeInsets.all(16.0), child: Container( color: Colors.blueAccent, child: const Text('Inside Padding', style: TextStyle(color: Colors.white)), ), ), Row( mainAxisSize: MainAxisSize.min, children: const [ Text('Start'), Spacer(), Text('End'), ], ), ], ), ), ), ); } }
Output
A screen with a column of texts: 'Above SizedBox' and 'Below SizedBox' separated by vertical space, a blue box with padded text, and a row with 'Start' on the left and 'End' on the right separated by flexible space.
Common Pitfalls
Common mistakes when adding spacing in Flutter include:
- Using
SizedBoxwith zero width or height by mistake, which adds no space. - Forgetting to wrap widgets in
Paddingwhen inner spacing is needed. - Using
Spaceroutside of flex containers likeRoworColumn, which causes errors.
dart
/* Wrong: Spacer outside flex container */ // This will cause an error Widget wrong = Spacer(); /* Right: Spacer inside Row */ Widget right = Row( children: const [ Text('Left'), Spacer(), Text('Right'), ], );
Quick Reference
| Widget | Purpose | Usage Example |
|---|---|---|
| SizedBox | Adds fixed space | SizedBox(height: 10) |
| Padding | Adds space inside widget boundary | Padding(padding: EdgeInsets.all(8)) |
| Spacer | Fills flexible space in flex layout | Row(children: [Text('A'), Spacer(), Text('B')]) |
Key Takeaways
Use SizedBox to add fixed width or height space between widgets.
Use Padding to add space inside a widget's boundary for better layout control.
Use Spacer only inside Row or Column to fill flexible space.
Avoid zero-sized SizedBox or Spacer outside flex containers to prevent layout issues.
Combining these widgets helps create clean and well-spaced Flutter UIs.