我有以下代码,需要在单击按钮时调用以显示错误文本,因为单击按钮时条件失败。
错误文本:
final confirmPassword = TextFormField(
controller: widget.confirmPasswordController,
obscureText: true,
decoration: InputDecoration(
prefixIcon: Icon(Icons.lock_open, color: Colors.grey),
hintText: 'Confirm Password',
errorText: validatePassword(widget.confirmPasswordController.text)
? "Password should contains more then 5 character"
: null,
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
),
);
按钮点击:
onPressed: () {
if (validateEmail(widget.emailController.text) &&
validatePassword(widget.passwordController.text) &&
validatePassword(widget.confirmPasswordController.text)) {
// launch new screen
} else {
// show the error text as above checks failed
}
}
我们如何才能实现这一目标? setState() 会帮助我们吗?
最佳答案
您可以通过使用带有key 的Form
小部件来实现它。喜欢
声明
GlobalKey<FormState> _globalFormKey = GlobalKey();
并将其设置为
Form(
key: _globalFormKey,
.
.
.
child:
)
在这里你可以使用 child
作为 TextFormField
并在按钮点击失败时写入。
_globalFormKey.currentState.validate()
了解更多信息 Form widget
~PS: Instead of check validation out of
TextFormField
, It has own propertyvalidator
. Search and use it.
关于flutter - 单击按钮时显示小部件的错误文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56847023/