Flutter中受密码保护的AlertDialog

时间:2020-11-02 05:59:02

标签: flutter dart

所以基本上我想在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();
            },
          ),

1 个答案:

答案 0 :(得分:0)

用以下代码替换 FlatButton

 FlatButton(
            child: Text('OK'),
            onPressed: () {
              String data = _textFieldController.value.text;
              
              if(data=='valid Password'){
                _getImage();
              }else{
                //Show Toast
                
                //Close the Dialog
                Navigator.of(context).pop();
              }
              
              
            },
          ),
相关问题