I am trying to add a dropdownbutton to my flutter app. The dropdown will have a static list of items.
This is the code I am trying to use:
DropdownButton<String>(
hint: const Text('Please choose transaction status'),
value: _trxnStatus,
onChanged: (_value) {
setState(() {
_trxnStatus = _value;
});
},
items: <String>[
'Select Status',
'Prospect',
'Listed',
'Under Contract',
'On Hold',
'Closed',
'Archived'
].map<DropdownMenuItem<String>>((String _value) {
return DropdownMenuItem<String>(
value: _value,
child: Text(_value),
);
}).toList(),
),
When I run this code, I am getting this error (sorry but it won’t let me copy the text):
Why am I getting this error?
Thanks for your help.
2
From the given code, everything seems normal except for the _trxnStatus
state variable.
The exception pretty much straightly says, you must need EXACTLY one DropdownMenuItem
matching the value of _trxnStatus
. Since you’re using the list of all possible values and mapping it to DropdownMenuItem
the only possible way to get to this crash-site, you’re initializing _trxnStatus
to a different value at the beginning.
Try defining the _trxnStatus
as nullable, and leave it null at first.
String? _trxnStatus;
Or set the initial value to a value inside the list.
String? _trxnStatus = "Select Status";
Hope this helps.
Try below code hope it’s help to you.
List declaration:
List<String> list = <String>[
'Select Status',
'Prospect',
'Listed',
'Under Contract',
'On Hold',
'Closed',
'Archived'
];
variable declartion:
String dropdownValue = list.first;
Dropdown Widget UI:
DropdownButton<String>(
hint: const Text('Please choose transaction status'),
value: dropdownValue,
onChanged: (value) {
setState(() {
dropdownValue = value!;
print('Selected Value = $dropdownValue');
});
},
items: list.map<DropdownMenuItem<String>>((value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
Read more about DropdownButton