[image] How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

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,
  ],
);

This question is related to image containers flutter stretch

The answer is


The following will fit the image to 100% of container width while the height is constant. For local assets, 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"),
    ),
  ),
)

Image fill modes:

  • Fill - Image is stretched

    fit: BoxFit.fill
    

    enter image description here


  • Fit Height - image kept proportional while making sure the full height of the image is shown (may overflow)

    fit: BoxFit.fitHeight
    

    enter image description here


  • Fit Width - image kept proportional while making sure the full width of the image is shown (may overflow)

    fit: BoxFit.fitWidth
    

    enter image description here


  • Cover - image kept proportional, ensures maximum coverage of the container (may overflow)

    fit: BoxFit.cover
    

    enter image description here


  • Contain - image kept proportional, minimal as possible, will reduce it's size if needed to display the entire image

    fit: BoxFit.contain
    

    enter image description here


I think that for your purpose Flex could work better than Container():

new Flex(
    direction: Axis.vertical,
    children: <Widget>[
      Image.asset(asset.background)
    ],
   )

For filling, I sometimes use SizedBox.expand


Visit https://youtu.be/TQ32vqvMR80 OR

For example if parent contrainer has height: 200, then

Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: NetworkImage('url'),
                fit: BoxFit.cover,
              ),
            ),
          ),

None of the above answers worked for me. And since there is no accepted answer, I found the following extended my image from horizontal edge to horizontal edge:

Container ( width: MediaQuery
                    .of(context)
                    .size
                    .width,
                child: 
                  Image.network(my_image_name, fit: BoxFit.fitWidth )
              )

Try setting contentPadding

ListTile(
  contentPadding: EdgeInsets.all(0.0),
  ...
)

To make an Image fill its parent, simply wrap it into a FittedBox:

FittedBox(
  child: Image.asset('foo.png'),
  fit: BoxFit.fill,
)

FittedBox here will stretch the image to fill the space. (Note that this functionality used to be provided by BoxFit.fill, but the API has meanwhile changed such that BoxFit 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 an Image – and use decoration/foregroundDecoration fields.

To make the Container will its parent, it should either:

  • have no child
  • have alignment property not null

Here's an example that combines two images and a Text in a single Container, while taking 100% width/height of its parent:

enter image description here

Container(
  foregroundDecoration: const BoxDecoration(
    image: DecorationImage(
        image: NetworkImage(
            'https://p6.storage.canalblog.com/69/50/922142/85510911_o.png'),
        fit: BoxFit.fill),
  ),
  decoration: const BoxDecoration(
    image: DecorationImage(
        alignment: Alignment(-.2, 0),
        image: NetworkImage(
            'http://www.naturerights.com/blog/wp-content/uploads/2017/12/Taranaki-NR-post-1170x550.png'),
        fit: BoxFit.cover),
  ),
  alignment: Alignment.bottomCenter,
  padding: EdgeInsets.only(bottom: 20),
  child: Text(
    "Hello World",
    style: Theme.of(context)
        .textTheme
        .display1
        .copyWith(color: Colors.white),
  ),
),

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

//gets the screen width and height
double Width = MediaQuery.of(context).size.width;
double Height = MediaQuery.of(context).size.height;

Widget background = new Image.asset(
  asset.background,
  fit: BoxFit.fill,
  width: Width,
  height: Height,
);

return new Stack(
  children: <Widget>[
    background,
    foreground,
  ],
);

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


Inside your Stack, you should wrap your background widget in a Positioned.fill.

return new Stack(
  children: <Widget>[
    new Positioned.fill(
      child: background,
    ),
    foreground,
  ],
);

For me, to develop for web, works fine the following:

Image(
  image: AssetImage('lib/images/portadaSchamann5.png'),
  alignment: Alignment.center,
  height: double.infinity,
  width: double.infinity,
  fit: BoxFit.fill,
),

This worked for me

class _SplashScreenState extends State<SplashScreen> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: FittedBox(
        child: Image.asset("images/my_image.png"),
        fit: BoxFit.fill,
      ),);
  }
}

I ran into problems with just an FittedBox so I wrapped my Image in an LayoutBuilder:

LayoutBuilder( 
   builder: (_, constraints) => Image(
      fit: BoxFit.fill,
      width: constraints.maxWidth,
      image: AssetImage(assets.example),
   ),
)

This worked like a charm and I suggest you give it a try.
Of course you can use height instead of width, this is just what I used.


For me, using Image(fit: BoxFit.fill ...) worked when in a bounded container.


I set width and height of a container to double.infinity like so:

Container(
        width: double.infinity,
        height: double.infinity,
        child: //your child
)

Might not be exactly what the OP was looking for, but this page is where I found myself after looking for the problem, so sharing this for everyone with similar issue :)

Stack's fit property did the trick for my needs. Otherwise Image inside (OctoImageIn my case) was padded and providing other Image.fit values did not give any effect.

Stack(
  fit: StackFit.expand, 
  children: [
    Image(
      image: provider,
      fit: BoxFit.cover,
    ),
    // other irrelevent children here
  ]
);

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to containers

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? How to get IP address of running docker container What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes? How to run a cron job inside a docker container? Connect to docker container as user other than root Starting a shell in the Docker Alpine container Docker error cannot delete docker container, conflict: unable to remove repository reference How can I keep a container running on Kubernetes? List only stopped Docker containers docker: "build" requires 1 argument. See 'docker build --help'

Examples related to flutter

Flutter Countdown Timer How to make an AlertDialog in Flutter? FlutterError: Unable to load asset Set the space between Elements in Row Flutter Flutter: RenderBox was not laid out Space between Column's children in Flutter How to change status bar color in Flutter? How can I add shadow to the widget in flutter? Flutter - The method was called on null Flutter- wrapping text

Examples related to stretch

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? CSS Div stretch 100% page height HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?