What is SizedBox in Flutter?
SizedBox is a simple box with a specified size. It can be used to: (1) add fixed empty space between widgets, (2) constrain a child to a specific width and height, or (3) create a placeholder with exact dimensions. It's one of the most frequently used widgets for layout spacing.
Basic Usage
You can create a SizedBox with just a width and/or height. If you provide a child, it will be forced to those dimensions.
Key Properties
- width: The width in logical pixels. If null, it will try to match the parent's width (if no child) or the child's width.
- height: The height in logical pixels. If null, it will try to match the parent's height (if no child) or the child's height.
- child: An optional widget to place inside the box. The child will be constrained to the given dimensions.
Using SizedBox for Spacing
The most common use is to add fixed gaps between widgets, especially in Columns and Rows.
Constraining a Child
Wrap a widget with SizedBox to give it a fixed size, overriding its own size preferences.
SizedBox.expand
Use SizedBox.expand() to create a box that expands to fill the available space from its parent.
Common Mistakes Beginners Make
- Using SizedBox with no dimensions and no child: It becomes invisible and takes no space.
- Assuming SizedBox always forces its size on the child: It does, but if the child has tighter constraints, it may not work (e.g., a Text with unbounded width).
- Using SizedBox for flexible spacing: If you need proportional spacing, use Expanded or Spacer instead.
Key Points to Remember
- SizedBox is perfect for fixed‑size gaps and constraining children.
- Use
widthandheightto set dimensions; omit one to let it be determined by parent/child. SizedBox.shrink()creates a zero‑sized box (useful for hiding widgets).SizedBox.expand()fills the available space.