Flutter: Stretching Background Images (FSBI)

I have an image that doesn’t match the aspect ratio of my device’s screen. I want to stretch the image so it completely fills the screen without cropping any part of it.

CSS has the concept of percentages, allowing us to set both height and width to 100%. However, Flutter doesn’t seem to have that concept, and hardcoding height and width values isn’t ideal, so I got stuck.

Here’s a basic example. We’ll adjust the image to fit 100% of the container’s width while keeping the height constant. For local assets, you can use AssetImage.

Container(
  width: MediaQuery.of(context).size.width,
  height: 100,
  decoration: BoxDecoration(
    image: DecorationImage(
      fit: BoxFit.fill,
      image: NetworkImage("https://picsum.photos/250?image=9"),
    ),
  ),
)

fit: BoxFit.fill

The image stretches to fill the container, ignoring its aspect ratio.



fit: BoxFit.fitHeight

The image maintains its aspect ratio while ensuring the full height is displayed (it might overflow horizontally).



fit: BoxFit.fitWidth

The image maintains its aspect ratio while ensuring the full width is displayed (it might overflow vertically).



fit: BoxFit.cover

The image maintains its aspect ratio, covering the container completely while potentially overflowing on one axis.



fit: BoxFit.contain

The image maintains its aspect ratio, scaling down if necessary, to ensure the entire image is visible within the container.


Post a Comment

Previous Next

نموذج الاتصال