Boxfit
- It works identically to the CSS object-fit property in web development.
Here is how each BoxFit option alters an image inside a container:
| BoxFit Options | Scaling Behaviour | Aspect Ratio | Image Cropping |
|---|---|---|---|
| BoxFit.cover | Scales up until the entire box is filled. | Maintained | Yes (Edges are cut off if ratios differ). |
| BoxFit.contain | Scales up/down until the entire image fits inside. | Maintained | No (Leaves blank/empty space). |
| BoxFit.fill | Stretches the image to match the exact box dimensions. | Distorted | No (Image will look squished or stretched). |
| BoxFit.fitWidth | Scales the image to match the exact width of the box. | Maintained | Yes (If the image becomes taller than the box). |
| BoxFit.fitHeight | Scales the image to match the exact height of the box. | Maintained | Yes (If the image becomes wider than the box). |
| BoxFit.none | Keeps the image at its original pixel size. | Maintained | Yes (Crops if original is larger than the box). |
| BoxFit.scaleDown | Acts like none if small, or contain if large. | Maintained | No (It only scales down, never up). |
- This is the most popular choice for UI components. It ensures your layout never has ugly empty gaps.
- It expands the image to fill every corner of the widget. If the parent box is a square and the image is a wide rectangle, the left and right sides will be cropped out.
- This is Flutter’s default behavior.
- It guarantees the user sees the entire image. However, if the image’s proportions don’t match the container, you will see blank space (letterboxing or pillarboxing) on the sides or top/bottom.
- It ignores the original aspect ratio completely. A circular profile photo forced into a wide rectangular container using BoxFit.fill will look heavily distorted.
- You apply it directly to an Image widget using the fit property:
Image.network(
'https://example.com',
width: 300,
height: 200,
fit: BoxFit.cover, // Change this to experiment with different behaviors
)
- If you are using a Container decoration instead, apply it to the DecorationImage:
Container(
width: 300,
height: 200,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('https://example.com'),
fit: BoxFit.cover,
),
),
)