Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - DropdownButton using keyValuePair

Tags:

flutter

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.

like image 586
Edmand Looi Avatar asked Apr 08 '18 17:04

Edmand Looi


1 Answers

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 enter image description here

like image 165
Raouf Rahiche Avatar answered Oct 08 '22 10:10

Raouf Rahiche