skip to Main Content

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


  1. you need to pass the value through the onChanged arguments like this

      DropdownButton<String>(
              //...
              onChanged:(String? val){
            //to convert the value to string do this
              String stringValue  = val.toString();
    
             debugPrint(stringValue);
    
      } ,
      )
    

    let me know in the comments if this works for you

    Login or Signup to reply.
  2. 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 doing onChanged.call(value), whereas your signature would require onChanged.call(value: value).

    You can easily fix this by slightly adjusting how you handle the callback. Try something like this:

    void onServerChanged({required String? value}) {
        //...
    }
    
    DropdownButton<String>(
      //...
      onChanged: (value) => onServerChanged(value: value),
    ),
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search