【问题标题】:There is a weird behavior of Stack with Fittedbox in layout?Stack with Fittedbox 在布局中有奇怪的行为吗?
【发布时间】:2018-05-04 15:55:34
【问题描述】:

按照卡片主题教程,编写flutter图库卡片示例代码

https://github.com/flutter/flutter/blob/master/examples/flutter_gallery/lib/demo/material/cards_demo.dart

这里是官方卡片示例

我不知道堆栈与fitbox结合的逻辑。为什么会有高度?我只是按照将底部、左右边距设置为 16.0、16.0、16.0 的教程进行操作。如果我没有任何误解,那就是父级和大小框之间的边距。为什么会有高度存在?有什么黑魔法代码吗?我只是想了解其中的逻辑。

我的结果图片

 var titleImage2 = new SizedBox(
      height: 200.0,
      child: new Stack(
        children : <Widget> [
            //new Text("First element" , style: new TextStyle(color: Colors.red),),
            new Positioned(
                //top: 0.0,
                left : 16.0, 
                right : 16.0, 
                bottom: 16.0,
                //width: 100.0,
              child: new FittedBox(
                fit : BoxFit.scaleDown, 
                alignment: Alignment.topLeft,
                child : new Container(
                  child: new Text(
                      "Hello world"
                  ),
                )
              ),
            )],
      ),
); 

总结:为什么只设置left,right,bottom到margin 16.0,它会出现一个现有的高度?我是flutter的新手

left : 16.0, 
right : 16.0, 
bottom: 16.0,

奇怪的图片

【问题讨论】:

    标签: layout stack material-design flutter


    【解决方案1】:

    我无法告诉您实现这一点的实际算法的细节,但我可以告诉您原因 - 因为您使用的是 FittedBox。 FittedBox 会根据父项和子项的约束进行各种计算,以尝试将您的项目适合父项。它对于具有特定纵横比但对其大小没有限制的图像之类的东西很有用。

    因为您有一个文本作为 FittedBox 的子项,所以它可能无法计算它可以缩放到的大小 - 我不知道 Text 会报告什么(我忽略了容器,因为它基本上只是代表布局如果它没有设置宽度和高度,则给它的孩子)。尝试将其设置为 BoxFit.cover,您会看到会发生什么。但我不知道为什么它会选择那个特定的尺寸。

    除非您使用的是图像,否则我建议您移除 FittedBox;这是你所看到的原因。

    【讨论】:

    • 其实我测试了一遍又一遍。如果我设置了安装框的固定高度,它将使用固定高度。我试过box.cover。似乎仍然出现高度。感谢您的答复。我稍后会更新我的测试结果
    猜你喜欢
    • 2014-02-25
    • 1970-01-01
    • 2018-04-19
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多