在Flutter中,如何使按钮和文本字段具有相同的高度?

时间:2019-08-22 00:28:01

标签: flutter dart flutter-layout

enter image description here

我知道TextField具有TextStyle,该属性具有height属性,该属性只是基于fontSize的乘数,但是如何使所有小部件相同的高度(与字体大小无关)?

此外,还有以下等效方法(几乎所有其他编程语言):

btnLogin.height = txtPassword.height;

2 个答案:

答案 0 :(得分:5)

输出:(所有高度都完全相同)

enter image description here


我认为最好的方法是首先找出TextField的高度,然后将其用于RaisedButton,这里是完整的示例代码。

void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
  double _height = 56; // dummy height
  GlobalKey _globalKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    SchedulerBinding.instance.addPostFrameCallback((_) {
      setState(() {
        // height of the TextFormField is calculated here, and we call setState to assign this value to Button
        _height = _globalKey.currentContext.size.height;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          children: <Widget>[
            TextField(
              key: _globalKey,
              decoration: InputDecoration(hintText: "Email Adress"),
            ),
            TextField(decoration: InputDecoration(hintText: "Password")),
            SizedBox(height: 12),
            SizedBox(
              width: double.maxFinite,
              height: _height, // this is the height of TextField
              child: RaisedButton(
                onPressed: () {},
                child: Text("LOGIN TO MY ACCOUNT"),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

答案 1 :(得分:1)

为简单起见,您可以使用以下代码:

Container(
  height: 210 , // Your fixed height*3 here (70*3=210)
  width : double.infinity,  
  padding: EdgeInsets.symmetric(horizontal: 8.0), //Add padding as per your convenience 
  child : Column(
    children: <Widget>[
      Expanded(TextField([...])),
      Expanded(TextField([...])),
      Expanded(RaisedButton([...])),
      ],
    ),
  )

可以在小部件之间随意插入Divider Widget或SizedBox,以根据您的要求提供更整洁的外观。

提示:与您在问题中描述问题的方式相比,Flutter的方法略有不同,因此,我建议您在继续进行之前先查看Flutter与编码相关的视频/博客的更多信息。