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

Time:04-12

I am trying to setup password and email validation and I am getting the error above. Any help would be greatly appreciated. The error above is in the main.dart code and has been bolded in the code.

validator.dart code

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 code

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

CodePudding user response:

If you check validator it returns a nullable String.

{String? Function(String?)? validator}

You can convert your validators like

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

CodePudding user response:

Your validate functions accept strictly non-null parameters. Change your function signature to static String? validate(String? value) (note the question mark after the second String) and it'll match the required signature.

  • Related