英文:
Flutter DropDown Widget issue
问题
我有一个下拉菜单,我想显示国家,但我想要国家代码作为值。
class CountryDropdown extends StatefulWidget {
const CountryDropdown({Key? key}) : super(key: key);
@override
_CountryDropdownState createState() => _CountryDropdownState();
}
class _CountryDropdownState extends State<CountryDropdown> {
String _selectedCountry = "Austria";
List<DropdownMenuItem<String>> get dropdownItems {
List<DropdownMenuItem<String>> menuItems = [
const DropdownMenuItem(child: Text("Austria"), value: "au"),
const DropdownMenuItem(child: Text("Belgium"), value: "be"),
const DropdownMenuItem(child: Text("Croatia"), value: "hr"),
];
return menuItems;
}
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(10.0),
child: DropdownButton<String>(
value: _selectedCountry,
hint: const Text('Select a country'),
onChanged: (newValue) {
setState(() {
_selectedCountry = newValue!;
});
},
items: dropdownItems,
),
);
}
}
然而,如果我将列表更改为以下内容,它会起作用。
const DropdownMenuItem(child: Text("Austria"), value: "Austria"),
此外,如果我更改为以下内容,它也会起作用。
const DropdownMenuItem(child: Text("au"), value: "Austria"),
这是怎么回事?
英文:
I have a dropdown which I want to display countries but I want the value to the country code.
class CountryDropdown extends StatefulWidget {
const CountryDropdown({Key? key}) : super(key: key);
@override
_CountryDropdownState createState() => _CountryDropdownState();
}
class _CountryDropdownState extends State<CountryDropdown> {
String _selectedCountry = "Austria";
List<DropdownMenuItem<String>> get dropdownItems {
List<DropdownMenuItem<String>> menuItems = [
const DropdownMenuItem(child: Text("Austria"), value: "au"),
const DropdownMenuItem(child: Text("Belgium"), value: "be"),
const DropdownMenuItem(child: Text("Croatia"), value: "hr"),
];
return menuItems;
}
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(10.0),
child: DropdownButton<String>(
value: _selectedCountry,
hint: const Text('Select a country'),
onChanged: (newValue) {
setState(() {
_selectedCountry = newValue!;
});
},
items: dropdownItems,
),
);
However, if I change the list to this... it works.
const DropdownMenuItem(child: Text("Austria"), value: "Austria"),
Also, if I change to this it works....
const DropdownMenuItem(child: Text("au"), value: "Austria"),
What's going on here?
答案1
得分: 1
Sure, here's the translation:
因为您的下拉项中没有任何一个项的值为"Austria",就像您的初始值一样 String _selectedCountry = "Austria"; //更改为"au"
late String _selectedCountry;
@override
void initState() {
_selectedCountry = "au";
super.initState();
}
英文:
it is because none of your dropdown item has the value "Austria" like your initial value String _selectedCountry = "Austria"; //chage to "au"
late String _selectedCountry;
@override
void initState() {
_selectedCountry = "au";
super.initState();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论