I have a function called onServerChanged
. This was working fine when I did the below:
void onServerChanged(String? value) {
//...
}
DropdownButton<String>(
//...
onChanged: onServerChanged,
),
However, when I changed the function to this, it stopped working:
void onServerChanged({required String? value}) {
//...
}
This gives an error pointing the function call in the DropdownButton
:
The argument type ‘void Function({required String? value})’ can’t be assigned to the parameter type ‘void Function(String?)?’
I really like forcing myself to write the parameter name whenever I call a function so that refactoring doesn’t create silent errors. I tried adding the parameter to the function call in the DropdownButton
but it didn’t work. How would I fix this so I can still use named parameters here?
2
Answers
you need to pass the value through the onChanged arguments like this
let me know in the comments if this works for you
Changing your function signature to use a named parameter instead of a positional one causes the
DropdownButton
to call it incorrectly, since internally it’s doingonChanged.call(value)
, whereas your signature would requireonChanged.call(value: value)
.You can easily fix this by slightly adjusting how you handle the callback. Try something like this:
Now, you’re passing a callback that takes a positional value. That callback then calls your
onServerChanged
function with a named parameter, and everyone’s happy.