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

Flutter如何实现TextFormField获取焦点时修改suffixIcon颜色

解决方案

方案1:使用MaterialStateProperty直接配置(推荐,无需手动管理状态)

直接为InputDecoration的suffixIconColor属性传入状态响应式的颜色配置即可,Flutter会自动根据输入框的当前状态匹配对应颜色:

TextFormField(
  decoration: InputDecoration(
    hintText: '请输入密码',
    suffixIcon: const Icon(Icons.visibility_off),
    // 自动响应状态切换颜色
    suffixIconColor: MaterialStateColor.resolveWith((states) {
      // 聚焦状态返回指定颜色
      if (states.contains(MaterialState.focused)) {
        return Colors.blue;
      }
      // 默认状态返回灰色
      return Colors.grey;
    }),
    border: const OutlineInputBorder(),
  ),
)

注意:如果使用该方案,不要手动给suffixIcon对应的Icon组件设置color属性,否则会覆盖状态响应的配色规则,这也是你之前直接给图标设色后颜色固定不变的原因。

方案2:全局主题配置(批量生效,适合统一项目风格)

如果需要项目内所有输入框的后缀图标都遵循该配色规则,可以直接在全局主题中配置,无需逐个给输入框设置属性:

MaterialApp(
  theme: ThemeData(
    inputDecorationTheme: InputDecorationTheme(
      suffixIconColor: MaterialStateColor.resolveWith((states) {
        if (states.contains(MaterialState.focused)) {
          return Colors.blue;
        }
        return Colors.grey;
      }),
      // 可同时配置其他输入框通用样式,比如聚焦边框颜色
      focusedBorder: const OutlineInputBorder(
        borderSide: BorderSide(color: Colors.blue),
      ),
    ),
  ),
  home: const YourLoginPage(),
)

方案3:手动监听FocusNode(灵活适配复杂自定义逻辑)

如果后续还要在输入框聚焦/失焦时执行其他自定义操作,可以用FocusNode手动监听状态:

  1. 首先在State类中声明相关变量
class _LoginPageState extends State<LoginPage> {
  late final FocusNode _passwordFocusNode;
  bool _isPasswordFocused = false;
  // 其他变量
}
  1. 初始化监听并在页面销毁时释放资源
@override
void initState() {
  super.initState();
  _passwordFocusNode = FocusNode();
  _passwordFocusNode.addListener(() {
    setState(() {
      _isPasswordFocused = _passwordFocusNode.hasFocus;
    });
  });
}

@override
void dispose() {
  _passwordFocusNode.dispose();
  super.dispose();
}
  1. 绑定到输入框并配置图标颜色
TextFormField(
  focusNode: _passwordFocusNode,
  decoration: InputDecoration(
    hintText: '请输入密码',
    suffixIcon: Icon(
      Icons.visibility_off,
      color: _isPasswordFocused ? Colors.blue : Colors.grey,
    ),
    border: const OutlineInputBorder(),
  ),
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:45:02