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

如何修改TextFormField组件下划线的错误状态颜色?

Flutter 自定义TextFormField校验错误下划线颜色方案

你可以通过两种方式修改错误状态下的下划线颜色,按需选择即可:

仅单个输入框需要特殊样式选方式1,整个深色主题下所有输入框统一规范选方式2。

方式1:单个组件单独配置

直接在当前TextFormField的InputDecoration中配置errorBorder(错误状态未聚焦时的下划线)和focusedErrorBorder(错误状态聚焦时的下划线)即可,示例修改代码如下:

TextFormField(
  decoration: InputDecoration(
    labelText: AppLocalizations.key(context, 'formPassword'),
    icon: const Icon(Icons.lock), // 补充原代码缺失的右括号
    hintText: AppLocalizations.key(context, 'enterYourPassword'),
    // 新增错误边框配置,将颜色替换为你需要的颜色即可
    errorBorder: const UnderlineInputBorder(
      borderSide: BorderSide(color: Colors.deepPurple),
    ),
    focusedErrorBorder: const UnderlineInputBorder(
      borderSide: BorderSide(color: Colors.deepPurple, width: 2),
    ),
    // 可选:同步修改错误提示文本的颜色
    errorStyle: const TextStyle(color: Colors.deepPurple),
  ),
  validator: (val) {
    val = val.trim();
    if (validatePassword(val) == false) {
      return AppLocalizations.key(context, 'passwordNotAccepted');
    }
    password = val;
    return null;
  },
  initialValue: '',
  onSaved: (val) => {},
  keyboardType: TextInputType.visiblePassword,
  obscureText: true,
)

方式2:全局配置深色主题下所有输入框的错误样式

如果要统一整个APP深色主题下所有输入框的错误样式,不需要逐个组件修改,可以在MaterialApp的darkTheme中配置InputDecorationTheme:

MaterialApp(
  darkTheme: ThemeData(
    brightness: Brightness.dark,
    // 全局输入框样式配置
    inputDecorationTheme: const InputDecorationTheme(
      errorBorder: UnderlineInputBorder(
        borderSide: BorderSide(color: Colors.deepPurple),
      ),
      focusedErrorBorder: UnderlineInputBorder(
        borderSide: BorderSide(color: Colors.deepPurple, width: 2),
      ),
      errorStyle: TextStyle(color: Colors.deepPurple),
    ),
    // 其他主题配置...
  ),
  // 其他APP配置...
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:24:03