What is the purpose of the FittedBox widget in Flutter?
#widget#fittedbox#layout
Answer
Overview
scales and positions its child within itself, ensuring the child fits within its bounds — similar to how textFittedBox
text
BoxFitBasic Usage
dartContainer( 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
| Fit | Description |
|---|---|
text | Scale down to fit, maintain aspect ratio (default) |
text | Scale up to fill, may clip edges |
text | Stretch to fill — may distort |
text | Scale to match width, may overflow height |
text | Scale to match height, may overflow width |
text | No scaling, child at natural size |
text | Like text |
Use Case 1: Fit Text to Container
dartContainer( 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
dartSizedBox( 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
dartFittedBox( fit: BoxFit.contain, alignment: Alignment.centerLeft, // Position within the box child: Text('Left aligned'), )
Best Use Case: Use
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.textFittedBox