简体   繁体   中英

How to get two values from a DropdownButtonFormField

I need help getting two values from a DropdownButtonFormField. The dropdown form items is a list created from documents in Firestore. This is my Dropdown:

  return DropdownButtonFormField(
      isExpanded: true,
      decoration: textInputDecoration,
      value: _currentUser,

      hint: Text(
        'Select User',
      ),
      onChanged: (val) {
        setState(() => _currentUser = val);
        setState(() => UserDropdownList.some = val);
      },
      items: user.map((user){
        return DropdownMenuItem(
          value: user.userId,
          child: Text(user.name)
        );
      }).toList(),
    ); 

From my dropdown, I get the userId as the value while on the dropdown, the name is displayed as text. I would however like a second value that can take the name of the selected user alongside the userId. Please help!

The dropdownmenuitem only has one property for the value , you can do the following:

items: user.map((user){
  return DropdownMenuItem(
    value: ${user.userId}_${user.name},
    child: Text(user.name)
     );
  }).toList(),

This will give you the value with both the id and the name of the user.

Making references to the split method as pointed out by Peter

one can try this

items: user.map((user){
 return DropdownMenuItem(
value: user["your_data"].toString() + " " + user["another_data"].toString(), 
// output = your_data  another_data
child: Text(user.name)
 );
  }).toList(),

to get the two values separately

print(_currentUser.split(" ")[0]); // will print your data

print(_currentUser.split(" ")[1]); // will print another data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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