SizedBox 中的 Flutter 图像被父 Container 覆盖

问题描述 投票:0回答: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)),
              ),
            ),

问题在于图像资源忽略了大小框的尺寸并从周围容器中获取尺寸,从而使图像太大。

我不确定为什么会发生这种情况,除非它从小部件树的顶部获取它的大小,这似乎没有意义。

flutter flutter-layout
4个回答
1
投票

width
height
中删除
Container
SizedBox
,而是在
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
  ),
)

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
投票

当子容器小于父容器时,父容器不知道将其放置在哪里,因此会强制其具有相同的大小。如果在父容器中包含参数

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

0
投票
 Container(
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: Colors.white,
                  boxShadow: const [
                    BoxShadow(
                      color: Color.fromARGB(255, 142, 137, 137),
                      blurRadius: 3,
                    ),
                  ],
                  borderRadius: BorderRadius.circular(15.0),
                ),
                child: Image.asset(
                  'assets/images/amazon.png',
                  fit: BoxFit.cover,
                  height: 28,
                  width: 28,
                ),
              ),
© www.soinside.com 2019 - 2024. All rights reserved.