【发布时间】:2020-11-02 05:59:02
【问题描述】:
所以基本上我试图在 Flutter 的警报对话框中设置一个验证器(“确定”按钮),当它弹出时,它会显示带有输入和“确定”和“取消”按钮的 TextFormField。
如果您输入正确的密码并在警报对话框中单击“确定”,它将运行 _getImage() 函数,如果您取消,它只会将其从堆栈中弹出。
目前,“取消”可以正常工作,但我不确定如何验证 onPressed 中的“确定”按钮的输入。我不确定我是否使用下面的 TextFormField 正确执行此操作,或者我是否有不必要的代码。有没有简单的解决方案?
_showPasswordDialog() async {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Enter Password'),
content: TextFormField(
//not sure if i need this
initialValue: _phPassword,
controller: _textFieldController,
decoration: InputDecoration(hintText: 'Enter Password'),
maxLength: 15,
obscureText: true,
validator: (String value) {
if (value.isEmpty) {
return 'Password is Required';
}
//maybe not necessary for toString()
if (value == _pass.toString()) {
_getImage();
} else {
return 'Please type in Correct Password';
}
return null;
},
onSaved: (String value) {
_phPassword = value;
},
),
actions: [
FlatButton(
child: Text('Cancel'),
onPressed: () => Navigator.pop(context),
),
//this needs to validate if the typed value was the same as the
//hardcoded password, it would run the _getImage() function
//the same as the validator in the TextFormField
FlatButton(
child: Text('OK'),
onPressed: () {},
),
],
);
});
}
编辑:所以应该是这样的,对吗?
FlatButton(
child: Text('OK'),
onPressed: () {
String data = _textFieldController.value.text;
if (data == _pass) {
_getImage();
} else {
return 'Please type in Correct Password';
}
Navigator.of(context).pop();
},
),
【问题讨论】: