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

Flutter:如何在TextFormField中放置Icon与IconButton并调整位置

解决方案

你当前的问题是把图标和按钮都塞进了prefixIcon里,导致两者都显示在输入框左侧。要实现左侧图标、右侧按钮的布局,直接利用InputDecoration提供的prefixIcon和suffixIcon两个属性即可,无需用Row嵌套。

修改后的代码如下:

TextFormField(
  keyboardType: TextInputType.visiblePassword,
  obscureText: !_showPassword,
  decoration: InputDecoration(
    labelStyle: TextStyle(color: Colors.black87),
    labelText: 'Enter password',
    // 左侧锁定图标
    prefixIcon: Icon(Icons.lock),
    // 右侧密码可见性切换按钮
    suffixIcon: IconButton(
      icon: _showPassword ? Icon(Icons.lock_open) : Icon(Icons.lock),
      onPressed: () {
        setState(() {
          _showPassword = !_showPassword;
        });
      },
    ),
    border: OutlineInputBorder(),
  ),
);

说明

  • prefixIcon:专门用于设置输入框左侧的图标/控件
  • suffixIcon:专门用于设置输入框右侧的图标/控件
    这两个属性是Flutter为输入框左右布局预设的配置,直接分开使用就能达到你想要的效果。

内容的提问来源于stack exchange,提问作者Şahin Yakıcı

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:18:33