参数类型 'String? Function(String)' 无法分配给参数类型 'String? Function(String?)?'

The argument type 'String? Function(String)' can't be assigned to the parameter type 'String? Function(String?)?'

我正在尝试设置密码和电子邮件验证,但出现上述错误。任何帮助将不胜感激。上面的错误在main.dart代码中,并已在代码中加粗。

validator.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;
  }
}

main.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,
          ),
        ];
      }

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

如果你检查 validator 它 returns 一个可为 null 的字符串。

{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;
  }
}