3

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,
          ),
        ];
      }
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56

3 Answers3

7

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

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • Glad to help you out, you can check more about [validation-logic](https://docs.flutter.dev/cookbook/forms/validation#2-add-a-textformfield-with-validation-logic) – Md. Yeasin Sheikh Apr 12 '22 at 12:02
1

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.

Piotr Szych
  • 36
  • 1
  • 3
  • I have already tried that and it gives an error on IsEmpty saying: The property 'isEmpty' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.') or adding a null check to the target ('!') – Lloyd Wingrove Apr 12 '22 at 11:57
0

The validator returns a null when all conditions are met, so you should handle that like this

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