将包装在Flex中的TextField居中在Flutter的Column小部件中的Row小部件中

时间:2019-11-12 21:59:48

标签: android flutter

我试图将位于Colum小部件中的Row小部件中的两个元素居中。此代码中的最后一行很有趣。我注意到,当我从该行中删除“ Flexible(...)”小部件时,文本将水平居中。否则,两个元素都将停留在屏幕的左侧。我希望这两个元素都保持中心。我尝试将Flexible小部件包装到一个Container中,然后将该容器与中间对齐,Flutter不喜欢这样。

我正在寻找最后一行中的两个小部件以使其水平居中

void main() => runApp(MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Example 1"),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  child: Center(
                    child: ButtonBar(
                      children: <Widget>[
                        RaisedButton(
                          child: Text("Button"),
                        ),
                        RaisedButton(
                          child: Text("Button"),
                        )
                      ],
                    ),
                  ),
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                Container(
                  child: Center(
                    child: ButtonBar(
                      children: <Widget>[
                        RaisedButton(
                          child: Text("Button"),
                        ),
                        RaisedButton(
                          child: Text("Button"),
                        )
                      ],
                    ),
                  ),
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text("Email:"),
                Flexible(
                    child: TextField(
                  textAlign: TextAlign.justify,
                  decoration: InputDecoration(
                    border: InputBorder.none,
                    hintText: "Enter Email",
                  ),)),
              ],
            ),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          child: Text("clock"),
        ),
      ),
    ));

1 个答案:

答案 0 :(得分:2)

Row Widget将尝试使用尽可能多的空间(https://api.flutter.dev/flutter/widgets/Row-class.html) 如果将子级小部件包装在Flex中并将主轴居中,则会看到子级元素居中

Row(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    Flexible(
      flex: 1,
      child: Text("Email:"),
    ),
    Flexible(
      flex: 1,
      child: TextField(
        textAlign: TextAlign.justify,
        decoration: InputDecoration(
          border: InputBorder.none,
          hintText: "Enter Email",
        ),
      ),
    ),
  ],
),