0
0
Fluttermobile~5 mins

SizedBox and Padding in Flutter

Choose your learning style9 modes available
Introduction

We use SizedBox to create empty space or fix a widget's size. Padding adds space inside a widget around its content.

To add space between buttons or text in a layout.
To fix a widget's width or height to a specific size.
To make sure content doesn't touch the edges of the screen.
To separate widgets visually for better design.
To create empty gaps in a column or row.
Syntax
Flutter
SizedBox(
  width: double?,
  height: double?,
  child: Widget?,
)

Padding(
  padding: EdgeInsets,
  child: Widget,
)

SizedBox can have width, height, or both. If no child is given, it creates empty space.

Padding uses EdgeInsets to set space inside the widget around its child.

Examples
Creates an empty box 20 pixels wide and 20 pixels tall.
Flutter
SizedBox(width: 20, height: 20)
Fixes the width of the text widget to 100 pixels.
Flutter
SizedBox(width: 100, child: Text('Hello'))
Adds 10 pixels of space on all sides inside the padding around the text.
Flutter
Padding(padding: EdgeInsets.all(10), child: Text('Hi'))
Adds 20 pixels of space on left and right sides inside the padding around the icon.
Flutter
Padding(padding: EdgeInsets.symmetric(horizontal: 20), child: Icon(Icons.star))
Sample App

This app shows three widgets stacked vertically:

  • A text above a space.
  • A text with padding around it.
  • A button inside a fixed size box.

The SizedBox adds vertical space and fixes button size. The Padding adds space inside the text widget.

Flutter
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('SizedBox and Padding Example')),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text('Above SizedBox'),
              const SizedBox(height: 30),
              const Padding(
                padding: EdgeInsets.all(20),
                child: Text('Text with Padding'),
              ),
              const SizedBox(height: 30),
              SizedBox(
                width: 150,
                height: 50,
                child: ElevatedButton(
                  onPressed: () {},
                  child: const Text('SizedBox Button'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

If SizedBox has no child, it creates empty space.

Padding always needs a child widget to wrap.

Use EdgeInsets.symmetric or EdgeInsets.only for custom padding sides.

Summary

SizedBox controls space or fixes widget size.

Padding adds space inside a widget around its content.

Both help make layouts neat and readable.