Flutter:如何在列中将容器大小设置为wrap_content

时间:2019-11-28 07:24:02

标签: flutter flutter-layout

我想将Container的大小设置为动态,我的意思是wrap_content抖动如何做?

在下面的代码Container中,默认情况下采用全宽,但是我想将Container中的宽度设置为Text(),只要

Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        Container(
          margin: EdgeInsets.all(10),
          alignment: Alignment.center,
          color: Colors.orange[800],
          child: Text("Hello How are you"),
        ),
        Container(
          margin: EdgeInsets.all(10),
          alignment: Alignment.center,
          color: Colors.yellow[800],
          child: Text("Welcome"),
        )
      ],
    );

我明白了:

enter image description here

但是我想要这个输出:

enter image description here

4 个答案:

答案 0 :(得分:3)

包裹您的容器
    Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.all(10),
                    alignment: Alignment.center,
                    color: Colors.orange[800],
                    child: Text("Hello How are you"),
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center, 
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.all(10),
                    alignment: Alignment.center,
                    color: Colors.yellow[800],
                    child: Text("Welcome"),
                  ),
                ],
              )
            ],
          ), 

答案 1 :(得分:2)

enter image description here

最简单的解决方案是使用Align

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    Align(
      child: Container(
        margin: EdgeInsets.all(10),
        color: Colors.orange[800],
        child: Text("Hello How are you"),
      ),
    ),
    Align(
      child: Container(
        margin: EdgeInsets.all(10),
        color: Colors.yellow[800],
        child: Text("Welcome"),
      ),
    )
  ],
)

答案 2 :(得分:0)

最短的解决方案是,从alignment: Alignment.center,移除Container并将Column包裹在Center内,像这样,

 Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              margin: EdgeInsets.all(10),
              color: Colors.orange[800],
              child: Text("Hello How are you"),
            ),
            Container(
              margin: EdgeInsets.all(10),
              color: Colors.yellow[800],
              child: Text("Welcome"),
            )
          ],
        ),
      )

输出

enter image description here

答案 3 :(得分:0)

包装容器内容的最佳方式不是为该小部件设置任何高度。