Flutter's FittedBox: Scale Any Widget to Fit
FittedBox scales its single child to fit an allocated space, like CSS's `object-fit` but for any widget. It's perfect for making an icon fill a button or ensuring text fits a container. The footgun: it fails in unconstrained parents like a `Row` or `Column`.
WHY IT EXISTS In Flutter, a child widget might be naturally larger or smaller than the space its parent provides, leading to overflow errors or awkward empty space. FittedBox solves this by creating a scaling boundary, forcing the child to conform to the parent's allocated area.
THE MENTAL MODEL FittedBox is like a picture frame for any widget. It takes a single child and a fitting rule. It first asks its parent for the available space (the frame size). Then, it lets its child render at its natural size (the picture). Finally, it scales the child up or down to fit inside the frame according to the rule you provided, like 'contain' or 'cover'.
HOW IT WORKS FittedBox wraps a single child. During layout, it lets its child determine its own unconstrained size. It then takes the constraints from its own parent (the available width and height) and calculates a transformation to scale the child. The fit property, of type BoxFit, dictates this scaling. For example, BoxFit.contain scales the child as large as possible while keeping it fully visible. BoxFit.fill stretches the child to fill the box completely, which may distort its aspect ratio.
WHEN TO USE IT Use FittedBox when you need a child to adapt to a parent's size without manual calculations. It's ideal for responsive UIs, like making a Text widget's content effectively grow to fill a container, or ensuring an Icon perfectly fills a square button regardless of the icon's intrinsic size.
WHEN NOT TO USE IT The biggest footgun is using FittedBox inside a parent that provides unconstrained dimensions, like a Column (unconstrained height) or Row (unconstrained width). FittedBox needs to know the bounds it's fitting into. Without bounds, it throws a layout error. To fix this, wrap the FittedBox in a widget that provides constraints, like SizedBox or Expanded.
ONE CANONICAL EXAMPLE To make a title in a fixed-height card header as large as possible, wrap the Text widget in a FittedBox. The FittedBox gets the header's fixed dimensions and scales the entire text render object (not just the font size) to fit perfectly within those bounds, preventing overflow.
Read the original → api.flutter.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.