Flutter语言选择下拉框选中后空白仅显示提示文本问题
Hey there, let's fix that dropdown issue where your selected language doesn't show up! The core problem here is that your DropdownButton isn't bound to the selected value variable — it has no way to know which option is currently selected, so it keeps showing the hint text even after you pick an option.
Step 1: Add the value property to DropdownButton
You need to link the DropdownButton to your _selectedeLang (I assume this might be a typo and should be _selectedLang) variable using the value parameter. Here's the corrected code for your DropdownButton section:
DropdownButton( isExpanded: true, itemHeight: 50, icon: Icon(Icons.arrow_drop_down), iconSize: 40, underline: SizedBox(), // Add this line to bind the selected value value: _selectedeLang, hint: Padding( padding: const EdgeInsets.all(8.0), child: Text(AppLocalization.of(context).getTranslatedValues('selectlang'),style: TextStyle(fontSize: 15,color: Colors.black54),), ), onChanged: (Language language) { _changeLanguage(language); setState(() { _selectedeLang = language; }); }, items: Language.languageList() .map<DropdownMenuItem<Language>>((lang) => DropdownMenuItem( value: lang, child: Row( children: <Widget>[ Center(child: Text((lang.name),style: TextStyle(fontSize: 15),)) ], ), )) .toList(), ),
Step 2: Double-check your Language class
Make sure your Language class properly handles equality checks, otherwise the DropdownButton might not recognize the selected item as a match. You can override == and hashCode manually, or use Dart's data class syntax if you're on a recent SDK version. Example:
class Language { final String name; final String languageCode; final String countryCode; Language(this.name, this.languageCode, this.countryCode); static List<Language> languageList() { return [ Language('English', 'en', 'US'), Language('Malayalam', 'ml', 'IN'), ]; } // Override equality checks for proper dropdown matching @override bool operator ==(Object other) => identical(this, other) || other is Language && runtimeType == other.runtimeType && name == other.name && languageCode == other.languageCode && countryCode == other.countryCode; @override int get hashCode => name.hashCode ^ languageCode.hashCode ^ countryCode.hashCode; }
Step 3: Verify initial state
Ensure you initialize _selectedeLang properly in your widget's state. For example:
// Initialize as nullable to show the hint initially Language? _selectedeLang; // Or set a default language if you want one pre-selected: // Language _selectedeLang = Language.languageList()[0];
Why this works
By adding the value property, the DropdownButton now knows to display the item that matches _selectedeLang whenever the state updates (triggered by setState). Without this binding, it has no reference point for the selected item and falls back to showing the hint text.
内容的提问来源于stack exchange,提问作者Abhijith

