I have this DropdownButton
with two items in it's List
When i Select Value 2 i'd like it to show a value not contained in the list
Like this :
Is it even possible ?
It would look something like this :
DropdownButton<String>(
value: dropdownValue,
items: <String>[
'Value 1',
'Value 2',
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (String? newValue) {
setState(() {
dropdownValue = newValue!;
if (dropdownValue == 'Value 2') {
dropdownValue = 'Value Not in list of items';
}
});
},
),
As you can see I of course get an error if i set dropdownValue = 'Value Not in list of items';
as it's not in the List - but i'd like it to work :)
This works on the other hand, as expected:
if (dropdownValue == 'Value 2') {
dropdownValue = 'Value 1';
}
as 'Value 1'
is in the List - but i'd like to display a value not in the list when i click on Value 2
I hope someone can help ! : )
[for SEO sake here is the error]:
Assertion failed:
../…/material/dropdown.dart:880
items == null ||
items.isEmpty ||
value == null ||
items.where((DropdownMenuItem<T> item) {
return item.value == value;
}).length ==
1
"There should be exactly one item with [DropdownButton]'s value: Value Not in list of items. \nEither zero or 2 or more [DropdownMenuItem]s were detected with the same value"
If you just want to display some text when Value 2
is chosen, you can try hint
widget.
String hintValue = 'Select Value'; // ---- hint
var dropdownValue;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children: [
ElevatedButton(child: Text('Press here'), onPressed: null), // ---- ignore
DropdownButton<String>(
value: dropdownValue,
hint: Text(hintValue), // ---- hint
isExpanded: true,
items: <String>[
'Value 1',
'Value 2',
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (newValue) {
setState(() {
// ----- if Value 2 is selected
if (newValue == 'Value 2') {
hintValue = 'Value Not in list of items';
} else
hintValue = '$newValue';
});
},
),
],
));
}
Note : Documentation for using hint
widget