Flutter:如何使用 DropDownButton?

Flutter: how to use DropDownButton?

我正在尝试构建一个包含多个元素的 DropdownButton 小部件,但即使我在 Internet 上阅读了多个教程,我仍然惨遭失败。

我怎样才能创建一个包含 4 个元素的简单 DropdownButton?

感谢您的宝贵时间

这是我尝试过的:

import 'package:flutter/material.dart';

class ForgotPassScreen extends StatefulWidget {
  @override
  _ForgotPassScreenState createState() => _ForgotPassScreenState();
}

class _ForgotPassScreenState extends State<ForgotPassScreen> {
  int _value = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Dropdown Button"),
        ),
        body: Container(
          padding: EdgeInsets.all(20.0),
          child: DropdownButton(
              value: _value,
              items: [
                DropdownMenuItem(
                  child: Text("Item 0"),
                  value: 0,
                ),
                DropdownMenuItem(
                  child: Text("First Item"),
                  value: 1,
                ),
                DropdownMenuItem(
                  child: Text("Second Item"),
                  value: 2,
                ),
                DropdownMenuItem(
                  child: Text("Third Item"),
                  value: 3,
                ),
                DropdownMenuItem(
                  child: Text("Fourth Item"),
                  value: 4,
                )
              ],
              onChanged: (value) {
                setState(() {
                  _value = value;
                });
              }),
        ));
  }
}

所以这段代码基本上有 3 个部分。首先是存储图标和标题的 object。第二个是这些object的列表,你想要多少就多少。第三个是构造框的按钮本身
OBJECT

class Choice {
  const Choice({this.title, this.icon});

  final String title;
  final IconData icon;
}

列表

List<Choice> choices = <Choice>[
      const Choice(title: 'Profile', icon: Icons.account_circle),
      const Choice(title:"Log in", icon: Icons.exit_to_app),
    ]

弹出按钮

          PopupMenuButton<Choice>(
            color:Colors.white,
            onSelected: onItemMenuPress,
            itemBuilder: (BuildContext context) {
              return choices.map((Choice choice) {
                return PopupMenuItem<Choice>(
                    value: choice,
                    child: Row(
                      children: <Widget>[
                        Icon(
                          choice.icon,
                          color:Colors.black
                        ),
                        Container(
                          width: 10.0,
                        ),
                        Text(
                          choice.title,
                          style: TextStyle(),
                        ),
                      ],
                    ));
              }).toList();
            },
          )

这是创建按钮的最佳方式,因为您可以对其进行修改而无需更改每一段代码