Validation 如果我调用';设置状态';在';onChange';文本字段的
我有两个文本字段,电子邮件和密码。输入电子邮件后,用户进入密码字段,我显示默认消息“密码不得为空” 下面是密码文本字段小部件。我想在用户开始键入密码时隐藏此消息 注意:我必须使用Textfield小部件。 代码如下:Validation 如果我调用';设置状态';在';onChange';文本字段的,validation,flutter,dart,error-handling,textfield,Validation,Flutter,Dart,Error Handling,Textfield,我有两个文本字段,电子邮件和密码。输入电子邮件后,用户进入密码字段,我显示默认消息“密码不得为空” 下面是密码文本字段小部件。我想在用户开始键入密码时隐藏此消息 注意:我必须使用Textfield小部件。 代码如下: @override Widget build(BuildContext context) { final TextEditingController emailController = new TextEditingController(text: this._email)
@override
Widget build(BuildContext context) {
final TextEditingController emailController =
new TextEditingController(text: this._email);
final TextEditingController passwordController =
new TextEditingController();
final submit = () async {
try {
FauiUser user = await fauiSignInUser(
apiKey: this.widget.firebaseApiKey,
email: emailController.text,
password: passwordController.text,
);
} catch (e) {
this.setState(() {
this._error = FauiError.exceptionToUiMessage(e);
//after typing email, when user presses <enter> or clicks in the Password field, the default message "Password must not be empty"
//is assigned to this._error and displayed below Password Textfield widget
this._email = emailController.text;
});
}
};
return Column(
children: <Widget>[
TextField(
controller: emailController,
autofocus: true,
decoration: InputDecoration(
labelText: 'EMail',
),
onSubmitted: (s) {
submit();
},
),
TextField(
controller: passwordController,
obscureText: true,
decoration: InputDecoration(
labelText: 'Password',
),
onSubmitted: (s) {
submit();
},
),
RaisedButton(
child: Text('Sign In'),
onPressed: submit,
),
]);
这将重建屏幕,消息将消失,但passwordController.text将被初始化,并且重建前输入的第一个字符将在该过程中丢失(例如,如果用户键入“hello”,则该值将变为“ello”)。
如何修复代码,使第一个字母不丢失?试试这个
TextField(
controller: passwordController,
obscureText: true,
decoration: InputDecoration(
labelText: 'Password',
hintText: 'Password must not be empty'
),);
我意识到通过使用Focus,我可以获得类似的结果:
child: TextField(
controller: passwordController,
obscureText: true,
decoration: InputDecoration(
labelText:"Password",
),
onSubmitted: (s) {
submit();
},
),
onFocusChange: (hasFocus) {
if (hasFocus) {
if (this._error.isNotEmpty) {
setState(() {
this._error = "";
});
}}
}),```
child: TextField(
controller: passwordController,
obscureText: true,
decoration: InputDecoration(
labelText:"Password",
),
onSubmitted: (s) {
submit();
},
),
onFocusChange: (hasFocus) {
if (hasFocus) {
if (this._error.isNotEmpty) {
setState(() {
this._error = "";
});
}}
}),```