how to set initial value to dropdown menu in flutter?
In dropdown menu I want to set initial value, currently its showing hint value "Select Language". I need the initial value to show there. Like my initial value is English, that should be the selected item in my Dropdown menu.
below is my code:
new DropdownButtonHideUnderline(
child: new DropdownButton<Language>(
hint: new Text("Select Language"),
value: selectedLanguage,
onChanged: (Language newValue) {
applic.onLocaleChanged(new Locale(newValue.languageCode,''));
setState(() {
selectedLanguage = newValue;
});
},
items: listLanguage.map((Language language) {
return new DropdownMenuItem<Language>(
value: language,
child: new Text(
language.languageName ,
style: new TextStyle(color: Colors.black),
),
);
}).toList(),
),
)
my list is initialized as:
List<Language> listLanguage =
<Language> [new Language("English", "en"),
new Language("French", "fr"),
new Language("Hindi", "hi"),
];
Language selectedLanguage;
DropDownButton: In Flutter, A DropDownButton is a material design button. The DropDownButton is a widget that we can use to select one unique value from a set of values. It lets the user select one value from a number of items. The default value shows the currently selected value.
To change the dropdown Button color in Flutter, simply wrap your DropdownButton widget inside the Container and provide the styling instructions inside the decoration property using the BoxDecoration widget.
To clear selected items in the DropDownList from Code behind, we can use the ClearSelection method. This method clears all the selected values.
For the dropdown to be able to recognize which languages are equal, you need to implement operator==
and hashCode
:
class Language {
final String code;
final String name;
const Language(this.name, this.code);
int get hashCode => code.hashCode;
bool operator==(Object other) => other is Language && other.code == code;
}
at least if you don't use const
like
const Language("English", "en"),
or reuse a previously created instance
selectedLanguage = listLanguage[0];
because without operator==
or const
selectedLanguage = new Language("English", "en");
will point to an entirely different Language
instance as these in listLanguage
where the dropdown has now way knowing they should be recognized as the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With