简体   繁体   English

Flutter - DropdownButton使用keyValuePair

[英]Flutter - DropdownButton using keyValuePair

I am new to flutter. 我是新来的人。 I am trying to create a dropdownbutton that takes a list of keyValuePairs. 我正在尝试创建一个带有keyValuePairs列表的下拉按钮。 When a user selects an item from the list I want to get the key of the selected item. 当用户从列表中选择项目时,我想获取所选项目的键。 I have search through the example but didn't see any way to do this. 我已经搜索了这个例子,但没有看到任何方法来做到这一点。 Is there another component I should use or is there a plugin to do just that. 是否有我应该使用的另一个组件,或者是否有插件可以做到这一点。 Thanks for your help on this. 感谢您的帮助。

i created a simple User Class 我创建了一个简单的用户类

class User {
  const User(this.id,this.name);

  final String name;
  final int id;
}

and a simple StatefulWidget that will show a dropdownbutton and Text 和一个简单的StatefulWidget,它将显示一个下拉按钮和Text

class MyApp extends StatefulWidget {
  State createState() => new MyAppState();
}

class MyAppState extends State<MyApp> {
  User selectedUser;
  List<User> users = <User>[const User(1,'Foo'), const User(2,'Bar')];

  @override
  void initState() {
    selectedUser=users[0];
  }
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(

        body: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Center(
              child: new DropdownButton<User>(
                value: selectedUser,
                onChanged: (User newValue) {
                  setState(() {
                    selectedUser = newValue;
                  });
                },
                items: users.map((User user) {
                  return new DropdownMenuItem<User>(
                    value: user,
                    child: new Text(
                      user.name,
                      style: new TextStyle(color: Colors.black),
                    ),
                  );
                }).toList(),
              ),
            ),
            new Text("selected user name is ${selectedUser.name} : and Id is : ${selectedUser.id}"),
          ],
        ),
      ),
    );
  }
}

and this is the final result 这是最后的结果 在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM