Home > Software engineering >  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:04-06

I am getting error

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

after dart 2 for a form field widget.

full code:

class MyFormField extends StatelessWidget {
  Function onTextChanged;
  Function formValidator;
  MyFormField(
      {
      required this.onTextChanged,
      required this.formValidator,
    });
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: TextFormField(
        style: TextStyle(fontWeight: FontWeight.bold),
        validator: formValidator, //***** Error Here
        keyboardType: TextInputType.number,
        onChanged: onTextChanged, //***** Error Here
      ),
    );
  }
}

CodePudding user response:

Change it to this

class MyFormField extends StatelessWidget {
  Function(String?) onTextChanged; //<=note
  Function(String?) formValidator; //<=note
  MyFormField(
      {
      required this.onTextChanged,
      required this.formValidator,
    });
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: TextFormField(
        style: TextStyle(fontWeight: FontWeight.bold),
        validator: (String? value) => formValidator(value), //***** Error Here
        keyboardType: TextInputType.number,
        onChanged: (String? value) => onTextChanged(value), //***** Error Here
      ),
    );
  }
}

Because the onChanged function, is called when a value is entered into the form, and this value is a string?, because sometimes no value is entered, and you are not sure, which could be null if left empty. And your validation function and onchanged functions, need a string to compute and do logic. They get these strings from the (String? value) in your form fields.

  • Related