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

use*_*950 3 dart flutter flutter-layout

在此处输入图片说明

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

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

btnLogin.height = txtPassword.height;
Run Code Online (Sandbox Code Playgroud)

Cop*_*oad 5

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

在此处输入图片说明


我认为最好的方法是先找出height 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"),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这似乎是可怕的做法-首先渲染并显示一些UI,然后立即更改其外观。 (4认同)