Arg type 'String? Function(String)' & 'void? Function(String)' can't assigned to param type String? Function(String?)? and void? Function(String?)?

Issue

I am getting argument type not assignable error in dart while checking the email value is empty or not the error which I am getting are

The argument type void Function(String) can’t be assigned to the parameter type void Function(String?)?.

and

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

These are the validator classes,

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

}

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

Here is the code giving the error

 List<Widget> buildInputs() {
    return <Widget>[
      TextFormField(
        key: Key('email'),
        decoration: InputDecoration(labelText: 'Email'),
        validator: EmailFieldValidator.validate, //this gives string error mentioned above
        onSaved: (String value) => _email = value, //getting void error mention above 
      ),
      TextFormField(
        key: Key('password'),
        decoration: InputDecoration(labelText: 'Password'),
        obscureText: true,
        validator: PasswordFieldValidator.validate,  // getting string error mentioned above
        onSaved: (String value) => _password = value, //getting void error mention above 
      ),
    ];
  }

Solution

This is a problem faced after the Null Safety thing came to flutter. I just normally cast it as a String to use it. Sometimes it gives out errors but not errors which will potentially break your app.

onSaved: (String? value) => _email = value as String,


static String? validate(String? value) {
String valueString = value as String;
// Do Your Usual thing over here like checking if it's empty}

Answered By – Kushal agrawal

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *