You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter如何在Column中垂直排列两个TextField并在屏幕居中显示

实现方案

你只需要调整原代码的布局结构,同时抽离通用的输入框样式保证两个TextField样式完全一致即可,修改后的完整代码如下:

class _TelaPrincipalState extends State<TelaPrincipal> {
  // 抽离通用输入框装饰样式,保证两个输入框样式完全同步
  final InputDecoration _commonInputDeco = const InputDecoration(
    fillColor: Colors.white,
    filled: true,
    contentPadding: EdgeInsets.symmetric(vertical: 8, horizontal: 8),
  );
  // 抽离通用输入框文字样式
  final TextStyle _commonTextStyle = const TextStyle(color: Colors.black);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('My App'),
        ),
        
        body: Center(
          child: Container(
            width: 250.0,
            // 移除原有的固定height属性,适配两个输入框的高度
            child: Column(
              // 让Column高度仅包裹内部内容,配合外层Center实现整体居中
              mainAxisSize: MainAxisSize.min,
              children: [
                TextField(
                  decoration: _commonInputDeco.copyWith(
                    labelText: 'Insert first input',
                  ),
                  style: _commonTextStyle,
                ),
                // 两个输入框的间距,可自行调整数值
                const SizedBox(height: 16),
                TextField(
                  decoration: _commonInputDeco.copyWith(
                    labelText: 'Insert second input',
                  ),
                  style: _commonTextStyle,
                ),
              ],
            ),
          ),
        ));
  }
}

核心调整说明

  • 把输入框的通用样式抽离成独立变量,后续修改样式时两个输入框会同步更新,彻底避免样式不一致的问题
  • Column设置mainAxisSize: MainAxisSize.min后,不会撑满整个屏幕高度,配合外层的Center组件即可实现两个输入框整体在屏幕居中展示的效果
  • 输入框之间的间距可以通过修改SizedBox的height参数自行调整

内容的提问来源于stack exchange,提问作者bilbo_bo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 13:45:03