Tom
Tom

Reputation: 413

Can't add a function to onChanged property

I'm developing an app and my current task is to implement localization for several languages. Now that I've translated most of it, I need to create a button that I would nest in the app bar that would drop down and offer the different languages. To that extent, I've followed this tutorial : https://www.youtube.com/watch?v=yX0nNHz1sFo&list=PLyHn8N5MSsgEfPAxCytQDPATDlHwpP5rE&index=3.

Now, since I plan on reusing this button for different pages, I created its own class, so far for good. But when comes time to add the onChanged property that would call the function responsible for language switching, it doesn't work. In fact, I can't call any function at all. Here's the code snippet:

class LanguageButton extends StatelessWidget {
  void changeLanguage(Language lang) {
    print(lang.languageCode); //placeHolder
  }

  Widget build(BuildContext context) {
    return DropdownButton(
      underline: SizedBox(),
      onChanged: (Language lang) {
        changeLanguage(lang);
      },
      icon: Icon(
        Icons.language,
        color: Colors.white,
      ),
      items: Language.languageList()
          .map<DropdownMenuItem<Language>>((lang) => DropdownMenuItem(
              value: lang,
              child: Row(children: [
                Text(lang.flag),
                Text(lang.language),
              ])))
          .toList(),
    );
  }
}

Which returns the error The argument type 'void Function(Language)' can't be assigned to the parameter type 'void Function(Language?)?'.. I've tried replacing by onChanged: ()=>print('hello') but it's still not working with a similar error message.

Any help is appreciated!

Upvotes: 0

Views: 60

Answers (1)

nvoigt
nvoigt

Reputation: 77304

The onChanged method of a DropdownButton (see the documentation) is a ValueChanged<T?>?. That means it can itself be null (for example if you don't set it at all), but if you set it, you need to set it to a method with the signature void Function(T?). Your method does not confirm to that signature, because it does not allow nulls.

Change yourmethod to:

void changeLanguage(Language? lang) {

and either pass it directly:

onChanged: changeLanguage,

or make the anonymous method have a nullable parameter, too:

onChanged: (Language? lang) {
    changeLanguage(lang);
  },

Upvotes: 1

Related Questions