I am new to flutter. I am trying to create a dropdownbutton that takes a list of 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With