Cameron Browne
Cameron Browne

Reputation: 99

how do you map index value to text for dropdownButton

In flutter I how do you map index to string. Example I have a List for numbers. I want to display text and capture the value in the back ground that would be numbers. I am using Dropdown menu item but you can only pass one value. final List nums = ['1', '2', '3','4','5', '6',]

DropdownButton(
 items: nums.map((e) {
  return DropdownMenuItem(
   value: e, 
   child: Text(e));
 }).toList(),
);

I want to do something like: final List nums = ['1': 'one', '2': 'two', '3': 'three','4': 'four','5': 'five', '6': 'six']; i represent the number e represent the text

DropdownButton(
     items: nums.map((i, e) {
      return DropdownMenuItem(
       value: i, 
       child: Text(e));
     }).toList(),
    );

Upvotes: 0

Views: 1228

Answers (2)

Cameron Browne
Cameron Browne

Reputation: 99

To capture the index or incremental value for the the string value. You should use indexof. Here is an example:

final List nums = ['one', 'two', 'three','four', 'five', 'six'];
int dropdownValue;
DropdownButton(
 onChanged: (String newValue) {
     setState(() {
     dropdownValue = nums.indexOf(newValue) + 1; 
     });
 },
 items: nums.map((e) {
  return DropdownMenuItem(
   value: i, 
   child: Text(e));
 }).toList(),
);

Upvotes: 2

Progxy
Progxy

Reputation: 112

You could use the dropdown as here :

final Map nums = ['1': 'one', '2': 'two', '3': 'three','4': 'four','5': 'five', '6': 'six'];
String dropdownValue = nums["one"]; //set the dropdown's default value
DropdownButton(
 value: dropdownValue,
 onChanged: (String newValue) {
     setState(() {
     dropdownValue = nums[newValue]; //update the dropdown's value
     });
 },
 items: nums.map((i, e) {
  return DropdownMenuItem(
   value: i, 
   child: Text(e));
 }).toList(),
);

Upvotes: 0

Related Questions