简体   繁体   English

如何让 Stack 小部件将自身约束到 Flutter 中的定位子项?

[英]How to have a Stack widget constrain itself to a Positioned child in Flutter?

In this code, I try to draw a Text widget within a Stack widget.在这段代码中,我尝试在 Stack 小部件中绘制一个 Text 小部件。 However, Stack widgets do not size themselves to positioned widgets, so the text gets cut off.但是,Stack 小部件不会根据定位的小部件调整自己的大小,因此文本会被截断。

How can the text be positioned while still contributing to the Stack's size?如何在仍然影响堆栈大小的同时定位文本?

return Column(
  children: <Widget>[
    Stack(
      children: <Widget>[
        Container(height:20, width: 20, color: Colors.green,),
        Positioned(
          top: 10,
          child: Text('Does not render because the stack is only 20x20'),
        )
      ],
    ),
    Container(height:40, width: 40, color: Colors.red,)
  ],
);

As mentioned in the documentation "The stack sizes itself to contain all the non-positioned children, which are positioned according to alignment (which defaults to the top-left corner in left-to-right environments and the top-right corner in right-to-left environments).", So we can't constraint stack itself to positioned widgets. 如文档中所述:“堆栈的大小本身将包含所有未定位的子项,这些子项根据对齐方式定位(在从左到右的环境中,默认值为左上角;在左环境)。”,因此我们不能将堆栈本身约束到定位的小部件。 But I think setting overflow to Overflow.visible will work for you. 但是我认为将Overflow设置为Overflow.visible会为您工作。

return Column(
  children: <Widget>[
    Stack(
      overflow: Overflow.visible,
      children: <Widget>[
        Container(height:20, width: 20, color: Colors.green,),
        Positioned(
          top: 10,
          child: Text('Does not render because the stack is only 20x20'),
        )
      ],
    ),
    Container(height:40, width: 40, color: Colors.red,)
  ],
);

The Overflow property was deprecated so now use this property:不推荐使用 Overflow 属性,因此现在使用此属性:

 clipBehavior: Clip.antiAliasWithSaveLayer,

Example:例子:

return Column(
  children: <Widget>[
    Stack(
      clipBehavior: Clip.antiAliasWithSaveLayer,
      children: <Widget>[
        Container(height:20, width: 20, color: Colors.green,),
        Positioned(
          top: 10,
          child: Text('Does not render because the stack is only 20x20'),
        )
      ],
    ),
    Container(height:40, width: 40, color: Colors.red,)
  ],
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM