Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter image in SizedBox is overridden by parent Container

I am trying to place an image in the center of a box (container with border). The image size is set by surrounding it with a sized box, the the border or box is being created by surrounding that with a container with box decoration like this:

            InkWell(
              child: Container(
                  decoration: BoxDecoration(border: Border.all()),
                  height: 50,
                  width: 70,
                  child: SizedBox(
                      height: 10,
                      width: 10,
                      child: Image.asset('assets/store_physical.png',
                          fit: BoxFit.cover)),
              ),
            ),

The problem is that the image asset it ignoring the dimensions of the sized box and taking the size from the surrounding container making the image too big.

I am not sure why this is happening unless it gets it size from the top of the widget tree which doesn't seem to make sense.

like image 422
Nicholas Muir Avatar asked Oct 19 '25 12:10

Nicholas Muir


2 Answers

When the child container is smaller than the parent, the parent doesn't know where to place it, so it forces it to have the same size. If you include the parameter alignment in the parent container, it will respect the size of the child Container:

InkWell(
      child: Container(
          alignment: Alignment.topLeft, //Set it to your specific need
          decoration: BoxDecoration(border: Border.all()),
          height: 50,
          width: 70,
          child: SizedBox(
              height: 10,
              width: 10,
              child: Image.asset('assets/store_physical.png',
                  fit: BoxFit.cover)),
      ),
    ),
like image 187
JAgüero Avatar answered Oct 22 '25 04:10

JAgüero


Remove width and height from Container and SizedBox, instead provide it in Image.asset()

Container(
  decoration: BoxDecoration(border: Border.all(color: Colors.blue, width: 5)),
  child: Image.asset(
    'assets/store_physical.png',
    fit: BoxFit.cover,
    height: 50, // set your height
    width: 70, // and width here
  ),
)
like image 34
CopsOnRoad Avatar answered Oct 22 '25 02:10

CopsOnRoad