Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,
          ),
        ];
      }
like image 288
Lloyd Wingrove Avatar asked Oct 18 '25 13:10

Lloyd Wingrove


2 Answers

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

like image 198
Yeasin Sheikh Avatar answered Oct 20 '25 03:10

Yeasin Sheikh


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.

like image 26
Piotr Szych Avatar answered Oct 20 '25 02:10

Piotr Szych