Flutter DropDown 小部件问题

问题描述 投票:0回答:1

我有一个下拉列表,我想显示国家,但我想要国家代码的值。

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"),

这里发生了什么?

这是错误:

flutter dropdown
1个回答
0
投票

这是因为你的下拉项都没有像你的初始值那样的值“奥地利”

String _selectedCountry = "Austria"; //chage to "au"

late String _selectedCountry;

@override
void initState() {
  _selectedCountry = "au";
  super.initState();
}
© www.soinside.com 2019 - 2024. All rights reserved.