I have an image that doesn't match the aspect ratio of my device's screen. I want to stretch the image so that it fully fills the screen, and I don't want to crop any part of the image.
CSS has the concept of percentages, so I could just set height and width to 100%. But it doesn't seem like Flutter has that concept, and it's bad to just hard code the height and width, so I'm stuck.
Here's what I have (I'm using a Stack since I have something in the foreground of the image):
Widget background = new Container(
height: // Not sure what to put here!
width: // Not sure what to put here!
child: new Image.asset(
asset.background,
fit: BoxFit.fill, // I thought this would fill up my Container but it doesn't
),
);
return new Stack(
children: <Widget>[
background,
foreground,
],
);
The following will fit the image to 100% of container width while the height is constant. For local assets, use AssetImage
Image fill modes:
Fill - Image is stretched
Fit Height - image kept proportional while making sure the full height of the image is shown (may overflow)
Fit Width - image kept proportional while making sure the full width of the image is shown (may overflow)
Cover - image kept proportional, ensures maximum coverage of the container (may overflow)
Contain - image kept proportional, minimal as possible, will reduce it's size if needed to display the entire image
I think that for your purpose Flex could work better than Container():
For filling, I sometimes use SizedBox.expand
To make an Image fill its parent, simply wrap it into a
FittedBox
:FittedBox
here will stretch the image to fill the space. (Note that this functionality used to be provided byBoxFit.fill
, but the API has meanwhile changed such thatBoxFit
no longer provides this functionality.FittedBox
should work as a drop-in replacement, no changes need to be made to the constructor arguments.)Alternatively, for complex decorations you can use a
Container
instead of anImage
– and usedecoration
/foregroundDecoration
fields.To make the
Container
will its parent, it should either:alignment
property notnull
Here's an example that combines two images and a
Text
in a singleContainer
, while taking 100% width/height of its parent:Try setting
contentPadding
Your Question contains the first step, but you need width and height. you can get the width and height of the screen. Here is a small edit
You can also use Width and Height to size other objects based on screen size.
ex:
width: Height/2, height: Height/2 //using height for both keeps aspect ratio