Flutter中SizedBox中的图像被父容器Container覆盖

4

我正在尝试将一张图片放置在一个带边框的盒子(容器)中心。图片大小是通过将其包围在一个有大小的盒子中设置的,然后通过将其包围在具有盒子装饰的容器中来创建边框或盒子,例如:

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

问题在于图像资源忽略了尺寸框的尺寸,而是从周围容器中获取尺寸,导致图像过大。
我不确定为什么会出现这种情况,除非它从小部件树的顶部获取其大小,但这似乎没有意义。
3个回答

1
当子容器比父容器小时,父容器不知道该放在哪里,因此强制其具有相同的大小。如果在父容器中包含参数alignment,它将尊重子容器的大小:
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)),
      ),
    ),

1

我也遇到了同样的问题。你可以尝试将Image.asset放在另一个容器中,然后根据需要改变该容器的大小。

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

1
ContainerSizedBox中删除widthheight,而是在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
  ),
)

2
不幸的是,那样行不通。我仍然需要容器来设置边框。我尝试删除SizedBox并将尺寸仅应用于图像,但它仍然从容器继承。 - Nicholas Muir
1
请查看更新后的答案。现在您也可以添加边框。 - CopsOnRoad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接