im trying to make a dropdownbutton has elements from my database (mysql) and im getting this error
A value of type 'Object?' can't be assigned to a variable of type 'String?'.
this is my code :
String? selectedCategory;
List categoryItem=[];
....
DropdownButton(
value: selectedCategory,
hint: Text('Select category'),
items: categoryItem.map((category) {
return DropdownMenuItem(
value: category['name'],
child: Text(category['name']));
}).toList(),
onChanged: ( value){
setState(() {
selectedCategory=value;
});
},
isExpanded: true,
),
the problem exactly here :
onChanged: ( value){
setState(() {
selectedCategory=value;
});
i tried this :
onChanged: (String? newValue) {
setState(() {
selectedCategory = newValue!;
});
and didnt work
3
Answers
Change
to
Issue is just that its not setting the value as string. You need to parse the value as String and its good to go.
You can parse the object to string by many ways.
selectedCategory = value as String?
selectedCategory = value?+""
selectedCategory = value?.toString()
To fix this, you need to explicitly cast the value to String? in the onChanged callback. Here’s how you can do it: