BoxFit

  • It works identically to the CSS object-fit property in web development.

Direct Visual Comparison

Here is how each BoxFit option alters an image inside a container:

BoxFit OptionsScaling BehaviourAspect RatioImage Cropping
BoxFit.coverScales up until the entire box is filled.MaintainedYes (Edges are cut off if ratios differ).
BoxFit.containScales up/down until the entire image fits inside.MaintainedNo (Leaves blank/empty space).
BoxFit.fillStretches the image to match the exact box dimensions.DistortedNo (Image will look squished or stretched).
BoxFit.fitWidthScales the image to match the exact width of the box.MaintainedYes (If the image becomes taller than the box).
BoxFit.fitHeightScales the image to match the exact height of the box.MaintainedYes (If the image becomes wider than the box).
BoxFit.noneKeeps the image at its original pixel size.MaintainedYes (Crops if original is larger than the box).
BoxFit.scaleDownActs like none if small, or contain if large.MaintainedNo (It only scales down, never up).

The Big Three (Most Commonly Used)

1. BoxFit.cover (Best for backgrounds, profile pictures, and grid cards)

  • 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.

2. BoxFit.contain (Best for logos, diagrams, and full-screen image viewers)

  • 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.

3. BoxFit.fill (Rarely used)

  • It ignores the original aspect ratio completely. A circular profile photo forced into a wide rectangular container using BoxFit.fill will look heavily distorted.

How to use it in code

  • 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,
    ),
  ),
)