【问题标题】:Image gets cut when wrapped in a `Stack`包裹在“堆栈”中时图像被剪切
【发布时间】:2021-07-18 14:29:21
【问题描述】:

我正在设计一个在其上显示图像和文本的小部件。

为了将文本小部件放在图像顶部,我使用Stack,但是,一旦我用堆栈包裹小部件,图像的底部就会被剪切。

  1. 没有 Stack(这很好):
Widget body() {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: Container(
          width: 160,
          height: 200,
          child: Image.network(
            'https://picsum.photos/250?image=9',
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }

  1. Stack(不好,因为图片底部被切掉了):
 Widget body() {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: Container(
          width: 160,
          height: 200,
          child: Stack(
            children: [
              Image.network(
                'https://picsum.photos/250?image=9',
                fit: BoxFit.cover,
              ),
              Align(
                alignment: Alignment.bottomLeft,
                child: Text('Label'),
              )
            ],
          ),
        ),
      ),
    );
  }

任何想法为什么会发生这种情况以及如何解决它?

【问题讨论】:

    标签: android flutter flutter-layout


    【解决方案1】:

    好的,我发现如果图像包含在Container 中并提供height,它可以工作,如下所示:

    child: Stack(
        children: [
            Container(
            width: 160,
            height: 200,
            child: Image.network(
                'https://picsum.photos/250?image=9',
                fit: BoxFit.cover,
              ),
            ),
            Align(
            alignment: Alignment.bottomLeft,
            child: Text('Label'),
            )
        ],
    ),
             
    

    不知道为什么会这样,但我想这与图像在父小部件中未指定时无法正确计算其宽度/高度有关。

    【讨论】:

      【解决方案2】:

      使用fit: StackFit.expand, 让我知道它是否适合你。

      
        Widget body() {
          return Padding(
            padding: const EdgeInsets.all(8.0),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: Container(
                width: 160,
                height: 200,
                child: Stack(
                  fit: StackFit.expand,
                  children: [
                    Image.network(
                      'https://picsum.photos/250?image=9',
                      fit: BoxFit.cover,
                    ),
                    Align(
                      alignment: Alignment(-.8, .75),
                      child: Text(
                        'Label',
                      ),
                    )
                  ],
                ),
              ),
            ),
          );
        }
      

      【讨论】:

        猜你喜欢
        • 2023-03-03
        • 2021-09-10
        • 1970-01-01
        • 2016-04-25
        • 2019-04-19
        • 1970-01-01
        • 2011-09-12
        • 2016-07-22
        • 1970-01-01
        相关资源
        最近更新 更多