flutterflutter-layout

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.


Solution

  • 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
      ),
    )