Flutter中如何实现TextField左边显示标题右边输入

在Flutter中,我想实现一个表单输入框,左侧显示固定的标题文本(比如"用户名:"),右侧是TextField输入区域。尝试用Row包裹Text和TextField,但布局总是对不齐,特别是当标题文字长度不同时。请问如何优雅地实现这种左右布局?最好能保持整体美观,且在不同屏幕尺寸下适配良好。

2 回复

使用InputDecorationprefixprefixText属性实现左侧标题,例如:

TextField(
  decoration: InputDecoration(
    prefixText: '标题:',
  ),
)

或使用prefix放置自定义Widget。

更多关于Flutter中如何实现TextField左边显示标题右边输入的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在 Flutter 中,可以通过 RowInputDecorator 实现 TextField 左侧显示标题、右侧输入。以下是两种常用方法:

方法一:使用 Row 组合

Row(
  children: [
    Text('标题:', style: TextStyle(fontSize: 16)),
    SizedBox(width: 8), // 添加间距
    Expanded(
      child: TextField(
        decoration: InputDecoration(
          border: OutlineInputBorder(),
          hintText: '请输入内容',
        ),
      ),
    ),
  ],
)

方法二:自定义 InputDecoration

TextField(
  decoration: InputDecoration(
    labelText: '标题',
    border: OutlineInputBorder(),
    contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 16),
  ),
)

完整示例代码

Column(
  children: [
    // 方法一
    Padding(
      padding: EdgeInsets.all(16),
      child: Row(
        children: [
          Text('用户名:', style: TextStyle(fontSize: 16)),
          SizedBox(width: 12),
          Expanded(
            child: TextField(
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                hintText: '请输入用户名',
              ),
            ),
          ),
        ],
      ),
    ),
    
    // 方法二
    Padding(
      padding: EdgeInsets.all(16),
      child: TextField(
        decoration: InputDecoration(
          labelText: '密码',
          border: OutlineInputBorder(),
          contentPadding: EdgeInsets.all(12),
        ),
      ),
    ),
  ],
)

说明:

  1. 方法一更灵活,可以完全自定义标题样式和布局
  2. 方法二使用内置 labelText,样式与 Material Design 规范一致
  3. 通过 SizedBoxPadding 控制间距
  4. 使用 Expanded 让 TextField 占满剩余空间

选择哪种方式取决于具体设计需求。如需完全控制布局建议使用方法一,如需快速实现标准样式可用方法二。

回到顶部