我想在 Flutter 中构建一个 TextField,用户必须在其中输入他的名字,但我想强制他至少输入 2 个字符。
这是我的代码:
TextField(
autofocus: true,
textCapitalization: TextCapitalization.words,
textAlign: TextAlign.center,
decoration: InputDecoration(
labelStyle: TextStyle(color: Colors.blue[900]),
border: InputBorder.none,
hintText: 'VORNAME',
),
style: TextStyle(
color: Colors.blue[900],
fontWeight: FontWeight.w600,
fontSize: MediaQuery.of(context).size.width * 0.075),
cursorColor: Colors.greenAccent,
inputFormatters: <TextInputFormatter>[
WhitelistingTextInputFormatter(RegExp("[a-zA-ZÄäÖöÜü]")) //Only Text as input
],
onChanged: (value) {
userData.forename = value;
},
onSubmitted: (value) {
Navigator.of(context).push(
CupertinoPageRoute(builder: (context) => SurName()));
}),
我怎样才能实现这个目标? 预先感谢您!
本
最佳答案
对于文本字段验证,请使用 TextFormField 而不是 TextField。 TextFormField 需要用 Form 小部件包装(如果有两个或更多文本表单字段,您可以用表单小部件包装其父级小部件)。表单小部件需要 key 和 autovalidate bool 值(它是可选的,但建议显示消息当用户尚未验证时,一旦验证消息就会停止显示)。我们创建两个变量并将其分配给Form。然后我们需要一个验证器,我们在其中根据我们的要求进行验证。(如果需要添加更多验证,可以添加多个if条件。)。最后提交的字段,我们检查用户是否验证了表单,如果验证通过,我们执行所需的操作,否则我们将 autovalidate 变量设置为 true 以执行自动验证。
var formKey = GlobalKey<FormState>();
bool autoValidate = false;
Form(
key: formKey,
autovalidate: autoValidate,
child: TextFormField(
validator: (value){
return value.length < 2 ? 'Name must be greater than two characters' : null;
},
autofocus: true,
textCapitalization: TextCapitalization.words,
textAlign: TextAlign.center,
decoration: InputDecoration(
labelStyle: TextStyle(color: Colors.blue[900]),
border: InputBorder.none,
hintText: 'VORNAME',
),
style: TextStyle(
color: Colors.blue[900],
fontWeight: FontWeight.w600,
fontSize: MediaQuery.of(context).size.width * 0.075),
cursorColor: Colors.greenAccent,
inputFormatters: <TextInputFormatter>[
WhitelistingTextInputFormatter(RegExp("[a-zA-ZÄäÖöÜü]")) //Only Text as input
],
onChanged: (value) {
userData.forename = value;
},
onFieldSubmitted: (value){
if(formKey.currentState.validate()){
Navigator.of(context).push(
CupertinoPageRoute(builder: (context) => SurName()));
}else{
setState(() {
autoValidate=true;
});
}
},
),
),
关于flutter - 如何强制用户在 Flutter 的 TextField 中输入至少 2 个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60895191/