skip to Main Content

I am trying to fit an image to the entire space, I am wrapping the Image.asset into an Expanded Widget but the image does not covers the entire space, I have used all the options in BoxFit enum and it doesnt really change the way the application looks. Does any of you has an idea what can be changed?

this is the code of the body inside the Scaffold:

body: Column(
          children: [
            Container(
              width: MediaQuery.of(context).size.width,
              color: Colors.brown[200],
              padding: const EdgeInsets.all(20),
              alignment: Alignment.center,
              child: const Text('How I like my coffe...'),
            ),
            Container(
              color: Colors.brown[100],
              padding: const EdgeInsets.all(20),
              child: const CoffeePrefs(),
            ),
            Expanded(
              child: Image.asset(
                'assets/coffee-beans-bg.jpg',
                fit: BoxFit.fill, // Ensures the image fits the full width
              ),
            ),
          ],

And this is how it looks:

chrome web view

I have wraped the image inside a SizedBox, a FittedBox, and change the BoxFit enums.

2

Answers


  1. The attributes width and height must be applied on Image explicitly.
    You will find comments on flutter source code as follows.

    /packages/flutter/lib/src/widgets/image.dart

    If non-null, require the image to have this width or height.

    If null, the image will pick a size that best preserves its intrinsic aspect ratio.

    It is strongly recommended that either both the [width] and the [height] be specified, or that the widget be placed in a context that sets tight layout constraints, so that the image does not change size as it loads.

    Consider using [fit] to adapt the image’s rendering to fit the given width and height if the exact image dimensions are not known in advance.

    Here is an example:

    Widget build(BuildContext context) {
      Size size = MediaQuery.of(context).size;
      return Scaffold(
        body: Image.asset(
          'xxx.png',
          width: size.width,
          height: size.height,
          fit: BoxFit.fill,
        ),
      );
    }
    
    Login or Signup to reply.
  2. Add height and width to image

     width: double.maxFinite,
     height: double.maxFinite,
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search