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

Flutter TextField如何不使用FocusNode设置聚焦时的填充背景色

不依赖FocusNode实现TextField聚焦态填充色方案

完全可以不依赖自定义FocusNode实现该功能,Flutter的InputDecoration的fillColor属性原生支持MaterialStateColor类型,可自动响应组件的聚焦、错误等不同状态,不需要手动监听状态变化。

你当前代码不生效的核心原因是将fillColor设为了固定的Colors.grey,该值不会跟随组件状态变化。以下是修改后的实现代码:

final BorderRadius radius = BorderRadius.circular(16.0);
final OutlineInputBorder errorBorder = OutlineInputBorder(
  borderSide: const BorderSide(
    color: Colors.red,
    width: 2.0,
  ),
  borderRadius: radius,
);

return TextFormField(
    autofocus: false,
    style: Theme.of(context).textTheme.bodyText1,
    decoration: InputDecoration(
      filled: true,
      // 替换固定fillColor为MaterialStateColor动态适配状态
      fillColor: MaterialStateColor.resolveWith((states) {
        // 错误状态优先级最高
        if (states.contains(MaterialState.error)) {
          return Colors.red.shade50;
        }
        // 聚焦状态返回对应填充色
        if (states.contains(MaterialState.focused)) {
          return Colors.white; // 这里替换为你需要的聚焦态填充色
        }
        // 默认状态填充色
        return Colors.grey;
      }),
      border: OutlineInputBorder(
        borderSide: BorderSide.none,
        borderRadius: radius,
      ),
      focusedBorder: OutlineInputBorder(
        borderSide: const BorderSide(
          color: Colors.blue,
          width: 2.0,
        ),
        borderRadius: radius,
      ),
      focusedErrorBorder: errorBorder,
      errorBorder: errorBorder,
    ),
    onChanged: (String? v) {
      
    },
    validator: (String? v) {
      if (v != null && v.length > 3) {
        return '';
      }
      
      return null;
    },
    autovalidateMode: AutovalidateMode.onUserInteraction,
  );

如果需要全局生效所有TextField的填充色规则,可以直接在App的全局Theme配置中设置inputDecorationTheme的fillColor属性,不需要每个TextField单独配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:06:02