Use of a _dolarChanged(String text) void function generating an error message in onChanged

Asked

Viewed 73 times

0

I created the following function:

void _dolarChanged(String text) {
    if (text.isEmpty) {
      _clearAll();
      return;
    }

    final double dolar = double.parse(text);
    realController.text = (dolar * this.dolar).toStringAsFixed(2);
    euroController.text = (dolar * this.dolar / euro).toStringAsFixed(2);
}

To be used in a TextField in the onChanged within a widget, but the following error is occurring:

The argument type 'Function' can’t be Assigned to the Parameter type 'void Function()'

The call from the Widget:

buildTextField('Dolares', 'US\$ ', dolarController, _dolarChanged),
Widget buildTextField(
  String label,
  String prefix,
  TextEditingController controller,
  Function function,
) {
  return TextField(
    controller: controller,
    decoration: InputDecoration(
      labelText: label,
      labelStyle: TextStyle(color: Colors.amber),
      border: const OutlineInputBorder(),
      prefixText: prefix,
    ),
    style: TextStyle(
      color: Colors.amber,
      fontSize: 25,
    ),
    onChanged: function,
    keyboardType: TextInputType.number,
  );
}

Has anyone been through this mistake or knows how to fix it?

2 answers

3


The parameter onChanged of TextField expects an object of the type ValueChanged<String>.

Being this one typedef defined as:

typedef ValueChanged<T> = void Function(T value);

Then change your method to receive one Function(String):

Widget buildTextField(
  String label,
  String prefix,
  TextEditingController controller,
  Function(String) function,
) {
  return TextField(
    controller: controller,
    decoration: InputDecoration(
      labelText: label,
      labelStyle: TextStyle(color: Colors.amber),
      border: const OutlineInputBorder(),
      prefixText: prefix,
    ),
    style: TextStyle(
      color: Colors.amber,
      fontSize: 25,
    ),
    onChanged: function,
    keyboardType: TextInputType.number,
  );
}

Which is exactly what the error message informs:

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

1

You have two alternatives:

  • You can define your function by specifying the type of the parameter and the return, as follows:
[...]
  TextEditingController controller,
  void Function (String) function,
) {
[...]
  • Call the function manually where it is needed internally:
[...]
onChanged: (String a)=>function(a),
[...]

This error occurs because only Function is less restricted than a Function who accepts a string return void. To protect the programmer, this error is triggered.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.