如何在Container内的TextFormField中正确显示验证错误信息?
解决TextFormField错误信息显示异常问题
方案1:将错误信息显示在输入框右侧
把TextFormField和错误文本放在Row布局中,通过FormState获取验证状态,手动控制错误文本的显示位置:
Form( key: _formKey, child: Container( padding: EdgeInsets.all(16), child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: TextFormField( decoration: InputDecoration( labelText: '邮箱', border: OutlineInputBorder(), // 关闭默认下方错误提示,避免重复显示 ), autovalidateMode: AutovalidateMode.onUserInteraction, validator: (value) { if (value == null || value.isEmpty) { return '请输入邮箱'; } if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) { return '邮箱格式不正确'; } return null; }, ), ), // 动态显示右侧错误信息 Builder( builder: (context) { final field = Form.of(context)?.fields['email']; if (field?.hasError == true) { return Padding( padding: EdgeInsets.only(left: 8), child: Text( field.errorText ?? '', style: TextStyle(color: Colors.red, fontSize: 12), ), ); } return SizedBox.shrink(); }, ) ], ), ), )
方案2:高亮边框+侧边悬浮错误提示
利用Stack布局将错误信息固定在输入框边框旁,同时通过InputDecoration设置错误状态下的边框样式:
Form( key: _formKey, child: Container( padding: EdgeInsets.all(16), child: Stack( children: [ TextFormField( decoration: InputDecoration( labelText: '邮箱', border: OutlineInputBorder( borderSide: BorderSide(color: Colors.grey), ), // 错误状态下的边框样式 errorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red, width: 2), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red, width: 2), ), // 隐藏默认下方错误文本 errorStyle: TextStyle(height: 0), ), autovalidateMode: AutovalidateMode.onUserInteraction, validator: (value) { if (value == null || value.isEmpty) { return '请输入邮箱'; } if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) { return '格式错误'; } return null; }, ), // 错误信息悬浮在输入框右上角 Positioned( top: -8, right: -8, child: Builder( builder: (context) { final field = Form.of(context)?.fields['email']; if (field?.hasError == true) { return Container( padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2), decoration: BoxDecoration( color: Colors.red, borderRadius: BorderRadius.circular(4), ), child: Text( field.errorText ?? '', style: TextStyle(color: Colors.white, fontSize: 10), ), ); } return SizedBox.shrink(); }, ), ), ], ), ), )
关键注意事项
- 确保Container的padding和约束不会挤压TextFormField的布局空间,避免错误信息被截断。
- 若保留默认errorText,可通过
errorStyle调整行高、字体大小,errorMaxLines限制显示行数。 - 给TextFormField设置明确的标识(如在Form中指定字段名),能更精准地获取验证状态。
内容的提问来源于stack exchange,提问作者Helgato
相关产品推荐
相关产品推荐

