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

Flutter中如何修改TextFormField错误状态下的下划线颜色

修改TextFormField校验错误时下划线颜色的方法

你当前的代码仅配置了enabledBorder和focusedBorder,但当校验出错时,TextFormField会默认使用红色的errorBorder(未聚焦错误状态边框)和focusedErrorBorder(聚焦错误状态边框)。只需在InputDecoration中显式设置这两个边框的样式,就能替换默认的红色下划线。

修改后的完整代码示例:

TextFormField(
  autovalidateMode: AutovalidateMode.onUserInteraction,
  validator: (value) => validateCharacters(value),
  inputFormatters: [
    LengthLimitingTextInputFormatter(20),
  ],
  decoration: const InputDecoration(
    errorStyle: TextStyle(color: Colors.grey),
    enabledBorder: UnderlineInputBorder(
      borderSide: BorderSide(color: Colors.grey),
    ),
    focusedBorder: UnderlineInputBorder(
      borderSide: BorderSide(color: Colors.grey),
    ),
    // 配置错误状态下的边框
    errorBorder: UnderlineInputBorder(
      borderSide: BorderSide(color: Colors.grey),
    ),
    focusedErrorBorder: UnderlineInputBorder(
      borderSide: BorderSide(color: Colors.grey),
    ),
    hintText: 'Full Name',
    hintStyle: TextStyle(fontSize: 12),
  ),
  onChanged: (value) {
    setState(() {
      fullName = value.trim();
    });
  },
)

关键说明:

  • errorBorder:控制输入框未聚焦且校验错误时的下划线样式
  • focusedErrorBorder:控制输入框聚焦且校验错误时的下划线样式
    将这两个边框的borderSide.color设置为你需要的颜色(示例中为灰色),即可覆盖默认的红色效果。

内容的提问来源于stack exchange,提问作者It'sPhil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:15:54