Home > Net >  Passing onChanged Function to Radio results in 'Closure call with mismatched arguments'
Passing onChanged Function to Radio results in 'Closure call with mismatched arguments'

Time:10-25

I have the following build method in my stateful widget:

@override
  Widget build(BuildContext context) {
    return Column(children: [
      Padding(
          child: Container(
            child: Row(
              children: <Widget>[
                _myRadioButton(
                  title: genders[0],
                  value: genders[0],
                  onChanged: (newValue) =>
                      setState(() => {_groupValue = newValue, context.read<UserSignupForm>().gender = newValue}),
                ),
                _myRadioButton(
                  title: genders[1],
                  value: genders[1],
                  onChanged: (newValue) =>
                      setState(() => {
                        _groupValue = newValue, context.read<UserSignupForm>().gender = newValue}),
                ),
              ],
            ),
          ))
    ]);
  }

And this is my Radio row:

Row _myRadioButton({required String title, String? value, required Function onChanged}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Radio(
          value: value,
          groupValue: _groupValue,
          onChanged: onChanged(),
        ),
        Text(title)
      ],
    );
  }

However, I get the following runtime error when building the widget:

The following NoSuchMethodError was thrown building GenderField(dirty, state: _GenderFieldState#17448):
Closure call with mismatched arguments: function '_GenderFieldState.build.<anonymous closure>'
Receiver: Closure: (dynamic) => void
Tried calling: _GenderFieldState.build.<anonymous closure>()
Found: _GenderFieldState.build.<anonymous closure>(dynamic) => void

Any ideas how to correctly pass the onChanged method argument to the onChanged property?

CodePudding user response:

remove the parentheses when passing the function

Row _myRadioButton({required String title, String? value, required void Function(String) onChanged}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Radio(
          value: value,
          groupValue: _groupValue,
          onChanged: onChanged,
        ),
        Text(title)
      ],
    );
  }

CodePudding user response:

Here is a solution with no compilation/runtime errors:

  Row _myRadioButton({required String title, String? value, 
                      required Function(dynamic)? onChanged}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Radio(
          value: value,
          groupValue: _groupValue,
          onChanged: onChanged,
        ),
        Text(title)
      ],
    );
  }
  • Related