如何在Flutter中创建一个单选下拉列表?

soat7uwm  于 2023-02-20  发布在  Flutter
关注(0)|答案(1)|浏览(186)

我是一个flutter初学者。如何在Flutter中创建一个单选下拉列表?Like This
我试过了,但我没有得到我想要的。
字符串下拉值= 'Bahrain';

Container(
              width: 308,
              child: DropdownButton(
                // Initial Value
                value: dropdownvalue,

                // Down Arrow Icon
                icon: const Icon(Icons.keyboard_arrow_down),

                // Array list of items
                items: dropdownvalue.map((String dropdownvalue) {
                  return DropdownMenuItem(
                    value: dropdownvalue,
                    child: Text(dropdownvalue),
                  );
                }).toList(),
                // After selecting the desired option,it will
                // change button value to selected value
                onChanged: (String? newValue) {
                  setState(() {
                    dropdownvalue = newValue!;
                  });
                },
              ),
            ),
0x6upsns

0x6upsns1#

您应该有list of items和selectedItem来管理列表和选择状态。

class _YourState extends State<MyHomePage> {
  List<String> countries = [
    'Bahrain',
    'India',
    'Iraq',
    'America',
  ];

  String? dropdownvalue ;

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      body: Center(
        child: DropdownButton(
          // Initial Value
          value: dropdownvalue,
          icon: const Icon(Icons.keyboard_arrow_down),
          isExpanded: true,
          items: countries.map((String dropdownvalue) {
            return DropdownMenuItem(
              value: dropdownvalue,
              child: Text(dropdownvalue),
            );
          }).toList(),
          hint: Text('Country'),
          onChanged: (String? newValue) {
            setState(() {
              dropdownvalue = newValue!;
            });
          },
        ),
      ),
    );
  }
}

相关问题