Home > Enterprise >  The argument type 'Function' can't be assigned to the parameter type 'String? Fu
The argument type 'Function' can't be assigned to the parameter type 'String? Fu

Time:12-21

I got this error and i don't know what is the reason to solve it.

class PasswordTextFormField extends StatelessWidget {

  final Function validator;
  final String name;

  PasswordTextFormField({required this.name, required this.validator});

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      validator: validator, // here it gives the error
      decoration: InputDecoration(
        border: const OutlineInputBorder(),
        hintText: name,
      ),
    );
  }
}

and it gives this kind of error:

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

In case you didn't get what I said:

Screenshot

Thanks for any help!

CodePudding user response:

since validator can be null you have to provide ? in the callback function as

final Function? validator;

and use it as

 validator: validator!,

Similarly the function which you are passing should also be nullable

String? validateMyInput(){
  // your code
}

CodePudding user response:

The validator expects a function which has a nullable string argument and nullable string return type. Something like:

String? validatingFunction(String? text) {
}

Since you are not properly declaring your validator variable, you are getting this error. To fix this, change your variable declaration to:

final FormFieldValidator<String?> validator;

Read about validator and FormFieldValidator.

CodePudding user response:

this is because TextInputField require a function which expects a string value as a argument and return either null or a string. but you are trying to give it any function which does not match the type it requires. change your code as follows


  final String? Function(String value) validator;
  final String name;

  PasswordTextFormField({required this.name, required this.validator});

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      validator: validator, // here it gives the error
      decoration: InputDecoration(
        border: const OutlineInputBorder(),
        hintText: name,
      ),
    );
  }
} ````
  • Related