带有验证的表单进入AlertDialog

时间:2019-02-03 16:25:03

标签: android dart flutter

总体来说,我对flutter和dev很陌生。请耐心和友好;) 我正在尝试验证AlertDialog显示的字段(电子邮件地址)。 当用户按“发送”时,如果邮件地址格式错误,我希望我的应用程序在该字段下显示错误消息。 我在做什么错了?

我找到了这个link,但仍然无法理解和找到解决方案...

我尝试使用:

validator: (value) {
                  if (!validator.email(value)) {
                    return 'Badly formated address';
                  }
                },

我也尝试过:

validator: _validateEmail,

String _validateEmail(String value) {
  if (value.isEmpty) {
    // The form is empty
    return "Enter email address";
  }
  // This is just a regular expression for email addresses
  String p = "[a-zA-Z0-9\+\.\_\%\-\+]{1,256}" +
      "\\@" +
      "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
      "(" +
      "\\." +
      "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
      ")+";
  RegExp regExp = new RegExp(p);

  if (regExp.hasMatch(value)) {
    // So, the email is valid
    return null;
  }

  // The pattern of the email didn't match the regex above.
  return 'Email is not valid';
}

onPressed时调用的函数:

void _showDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: new Text("Email"),
          content: new TextFormField(
            autofocus: true,
            controller: emailController,
            keyboardType: TextInputType.emailAddress,
            //maxLength: 32,
            autovalidate: false,
            decoration: InputDecoration(
                icon: new Icon(Icons.mail, color: Colors.blue),
                border: UnderlineInputBorder(
                    borderRadius: BorderRadius.circular(1.0)),
                hintText: 'email address'),
          ),
          actions: <Widget>[
            // usually buttons at the bottom of the dialog
            new FlatButton(
              child: new Text("Cancel"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            new FlatButton(
                child: new Text("Send"),
                onPressed: () {
                  _sendPassword(emailController.text);
                  Navigator.of(context).pop();
                }),
          ],
        );
      },
    );
  }

预期结果: 如果电子邮件地址格式错误,则会向用户显示错误消息。 实际结果 : _sendPassword()总是被调用

0 个答案:

没有答案