How to get two values from a DropdownButtonFormField

Viewed 1050

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!

2 Answers

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
Related