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
Answers
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 toDropdownMenuItem
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.Or set the initial value to a value inside the list.
Hope this helps.
Try below code hope it’s help to you.
List declaration:
variable declartion:
Dropdown Widget UI:
Read more about DropdownButton