Question #329EasyWidgets & UI

What is the purpose of the FittedBox widget in Flutter?

#widget#fittedbox#layout

Answer

Overview

text
FittedBox
scales and positions its child within itself, ensuring the child fits within its bounds — similar to how
text
BoxFit
works for images.


Basic Usage

dart
Container(
  width: 100,
  height: 50,
  child: FittedBox(
    fit: BoxFit.contain,
    child: Text('Large Text That Would Overflow'),
  ),
)
// Text scales down to fit in the 100x50 container

BoxFit Options

FitDescription
text
contain
Scale down to fit, maintain aspect ratio (default)
text
cover
Scale up to fill, may clip edges
text
fill
Stretch to fill — may distort
text
fitWidth
Scale to match width, may overflow height
text
fitHeight
Scale to match height, may overflow width
text
none
No scaling, child at natural size
text
scaleDown
Like
text
contain
but never scales up

Use Case 1: Fit Text to Container

dart
Container(
  width: 80,
  height: 30,
  color: Colors.blue,
  child: FittedBox(
    fit: BoxFit.scaleDown,
    child: Text(
      'Hello Flutter!',
      style: TextStyle(color: Colors.white, fontSize: 20),
    ),
  ),
)

Use Case 2: Scale Icon to Fill

dart
SizedBox(
  width: 50,
  height: 50,
  child: FittedBox(
    fit: BoxFit.fill,
    child: Icon(Icons.star),
  ),
)

Use Case 3: Responsive Number Display

dart
// Number that scales to whatever space is available
FittedBox(
  fit: BoxFit.scaleDown,
  child: Text(
    '1,234,567',
    style: TextStyle(fontSize: 48, fontWeight: FontWeight.bold),
  ),
)

With alignment

dart
FittedBox(
  fit: BoxFit.contain,
  alignment: Alignment.centerLeft, // Position within the box
  child: Text('Left aligned'),
)

Best Use Case: Use

text
FittedBox
when you have a widget that may be larger than its container and you need it to scale down automatically — especially useful for dynamic text, icons, or widgets in responsive layouts.