Sub topic 11
Sizing and cropping images with BoxFit
This chapter assumes you can load an image with Image.asset or Image.network, that you know how BoxConstraints flow from parent to child, and that your project already declares assets/images/ in pubspec.yaml. It covers how an Image chooses its box, how BoxFit paints into that box, and the cases that surprise people.
Two separate decisions: the box and the fit
An Image widget makes two independent decisions:
- Box size. How large the widget is on screen, decided by its
width,height, and the constraints from its parent. - Fit. How the decoded pixels are scaled and cropped inside that box, decided by
fitandalignment.
Most sizing bugs come from mixing these up. fit never changes the widget's size. It changes only what is painted inside the box.
How the box is chosen
- With no
widthorheight, the image asks for its natural size in logical pixels, then the parent's constraints clamp it. A 1200 px wide photo in a phone-widthColumnis clamped to the screen width. In aRow, which gives unbounded width, it can overflow. - With only
widthor onlyheight, the other side follows the image's aspect ratio, as far as the constraints allow. - With both set, the box is exactly that size (again clamped by the parent), and the image may not match its aspect ratio. This is the case where
fitmatters. - Under tight constraints, such as inside
SizedBox,Expanded, orAspectRatio, the box is fixed by the parent. Yourwidthandheightare ignored if they conflict.
The seven BoxFit values
| Value | Behavior | Aspect ratio kept | Crops | Leaves empty space |
|---|---|---|---|---|
| `fill` | Stretches to the box | No | No | No |
| `contain` | Largest size that fits entirely inside | Yes | No | Yes |
| `cover` | Smallest size that covers the whole box | Yes | Yes | No |
| `fitWidth` | Width matches the box | Yes | If too tall | If too short |
| `fitHeight` | Height matches the box | Yes | If too wide | If too narrow |
| `none` | Natural size, no scaling | Yes | If larger | If smaller |
| `scaleDown` | Like `contain`, but never enlarges | Yes | No | Yes |
When you leave fit as null, Flutter paints the image as scaleDown. A small image therefore stays small in a large box, which surprises people who expect it to fill.
A gallery to see the differences
This app renders the same image with every BoxFit value in a fixed-size cell. It assumes assets/images/hero.png exists and is declared in pubspec.yaml. Use an image that is not square so the differences show.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: FitGallery()));
class FitGallery extends StatelessWidget {
const FitGallery({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('BoxFit gallery')),
body: GridView.count(
crossAxisCount: 2,
padding: const EdgeInsets.all(12),
mainAxisSpacing: 12,
crossAxisSpacing: 12,
children: [
for (final fit in BoxFit.values)
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: ColoredBox(
color: Colors.black12,
child: Image.asset(
'assets/images/hero.png',
width: double.infinity,
height: double.infinity,
fit: fit,
),
),
),
Text(fit.name, textAlign: TextAlign.center),
],
),
],
),
);
}
}The grey ColoredBox makes the box visible. With contain, fitWidth, fitHeight, none, and scaleDown, you can see grey bands where the image does not reach the edges. With cover and fill there are none.
Controlling which part survives a crop
cover, fitWidth, fitHeight, and none can crop. By default the crop is centered, so the middle of the image survives. The alignment parameter moves the anchor. This matters for portraits, where the face is usually in the upper part of the frame.
ClipRRect(
borderRadius: BorderRadius.circular(12),
child: Image.asset(
'assets/images/portrait.png',
width: 160,
height: 160,
fit: BoxFit.cover,
alignment: Alignment.topCenter,
),
)Alignment.topCenter keeps the top edge and removes the excess from the bottom. alignment also positions the image when it does not fill the box (contain, for example), so a contain image can sit at the left instead of the middle.
Rounded corners are not part of Image. Wrap it in ClipRRect, or paint it as a DecorationImage:
Container(
width: 200,
height: 120,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
image: const DecorationImage(
image: AssetImage('assets/images/hero.png'),
fit: BoxFit.cover,
),
),
)DecorationImage accepts the same fit and alignment values, and the decoration clips to the rounded shape. Use it for backgrounds. Use Image when you want semantics, loading builders, or error builders.
Fit and memory
fit only affects painting. The full image is still decoded at its original resolution unless you limit it. Use cacheWidth or cacheHeight to decode at a smaller size.
- Set the cache dimension to the logical size multiplied by the device pixel ratio, or slightly higher. A 300 px box on a 2x screen needs about 600 decoded pixels.
- Set only one of
cacheWidthandcacheHeight. The other follows the aspect ratio. If you set both, the decoder resizes to exactly those dimensions and can distort the image beforefitis applied. - With
cover, size the cache from the dimension that is scaled to the box, not the one that is cropped. For a wide image in a square box, the height fills the box, so usecacheHeight. AcacheWidthequal to the box width would leave the image too small after covering.
Image.asset(
'assets/images/hero.png',
width: 300,
height: 180,
fit: BoxFit.cover,
cacheWidth: 600,
)Common errors
- Image overflows a
Row. TheRowgives unbounded width, so the image uses its natural size. Wrap it inExpandedorFlexible, or set awidth. fithas no visible effect. The image has nowidthorheightand the box simply matches its aspect ratio, so there is nothing to fit. Give the box a size, or put the image in a tight parent such asSizedBoxorAspectRatio.- Image is stretched. You used
BoxFit.fill, or set bothcacheWidthandcacheHeightwith a different aspect ratio. - Small image stays small. The default is
scaleDown. Choosecontainorcoverto enlarge it. - Blurry image with
coverorfill. The source is smaller than the box on the device. Supply a larger asset or a resolution variant. Do not rely on scaling up. - Image does not appear in a
ListViewitem. If the image is inside aRowin a list tile, an unbounded width can cause layout errors. Constrain it withSizedBox.
Exercise
An Image.asset has width: 300, height: 300, and fit: BoxFit.cover. The source image is 1200 by 600 pixels. Which dimension is scaled to match the box, which dimension is cropped, and which cacheHeight avoids decoding more than needed on a 2x screen?
Show answer
The height is scaled to match the box, because the image must cover the full 300 by 300 area and the smaller side limits the scale. The width is cropped, so about half of the scaled image is lost, centered by default. On a 2x screen the height needs 600 decoded pixels, so cacheHeight: 600 is the right choice. The decoder keeps the aspect ratio and produces a 1200 by 600 image here, which means no saving for this particular source, but a larger source would shrink.
Exercise
You place an Image.network with fit: BoxFit.cover and no width or height inside a Row. The image is much wider than the screen and overflows. Name two ways to fix it.
Show answer
Wrap the image in Expanded (or Flexible) so the Row gives it a bounded width, or give the image an explicit width and height. Setting fit alone does not help, because fit only changes painting inside a box that already has a size.