dart 参数类型“String?无法将Function(String)'分配给参数类型'String?函数(String?)?'

i2loujxw  于 2023-05-20  发布在  其他
关注(0)|答案(3)|浏览(167)

我试图设置密码和电子邮件验证,我得到上面的错误。任何帮助将不胜感激。上面的错误出现在main.dart代码中,并在代码中以粗体显示。
验证器.dart代码

enum FormType { login, register }

class EmailValidator {
  static String? validate(String value) {
    return value.isEmpty ? "Email can't be empty" : null;
  }
}

class PasswordValidator {
  static String? validate(String value) {
    return value.isEmpty ? "Password can't be empty" : null;
  }
}

主.dart代码

List<Widget>buildInputs() {
        return [
          TextFormField(
            validator: **EmailValidator.validate**,
            decoration: InputDecoration(labelText: 'Email'),
            onSaved: (value) => _email = value,
          ),
          TextFormField(
            validator: **PasswordValidator.validate**,
            decoration: InputDecoration(labelText: 'Password'),
            obscureText: true,
            onSaved: (value) => _password = value,
          ),
        ];
      }
mi7gmzs6

mi7gmzs61#

如果选中validator,则返回一个可为空的String。
{String? Function(String?)? validator}
你可以像这样转换你的验证器

class EmailValidator {
  static String? validate(String? value) {
    return value==null ||  value.isEmpty ? "Email can't be empty" : null;
  }
}

class PasswordValidator {
  static String? validate(String? value) {
    return value==null ||value.isEmpty ? "Password can't be empty" : null;
  }
}
wxclj1h5

wxclj1h52#

validate函数严格接受非空参数。将函数签名更改为static String? validate(String? value)(注意第二个String后面的问号),它将匹配所需的签名。

lb3vh1jj

lb3vh1jj3#

当所有条件都满足时,验证器返回一个null,因此您应该这样处理它

static String? validateMobile(String? value) {
  //Indian Mobile number are of 10 digit only
    if (value!.length != 10) {
      return 'Mobile Number must be of 10 digit';
    } else {
      return null;
    }
  }

相关问题