I have to use a DropdownButton()
in my flutter app and I was getting some exceptions. Am I doing anything wrong and how do I go about fixing this?
...
class _CreateNewsArticleState extends State<CreateNewsArticle> {
String dropdownvalue = 'Publish';
var items = [
'Publish at 22:00',
'Publish in 9 hrs',
'Publish in 5 hrs',
'Publish in 3 hrs',
'Publish in 1 hr',
'Publish now'
];
@override
Widget build(BuildContext context) {
...
This is the flutter DropdownButton()
widget
DropdownButton(
value: dropdownvalue,
icon: Icon(Icons.arrow_forward_ios),
items: items.map((String items) {
return DropdownMenuItem(
value: items, child: Text(items));
}).toList(),
onChanged: (value) {
setState(() {
dropdownvalue = "value";
});
},
)
error
Object? value
Type: Object?
A value of type 'Object?' can't be assigned to a variable of type 'String'.
Try changing the type of the variable, or casting the right-hand type to 'String'.dartinvalid_assignment
CodePudding user response:
In your setState
you are not setting the var value
but a String "value"
.
setState(() {
dropdownvalue = value;
});
Also, keep in mind that your dropdownvalue
must be one of your values list or this will cause an Exception (There should be exactly one item with [DropdownButton]'s value
)
As mentioned by Maikzen declare your list as a List<String>
and the DropdrownMenuItems as DropdownMenuItem<String>
.
CodePudding user response:
Declare your list as List:
List<String> items = [
'Publish at 22:00',
'Publish in 9 hrs',
'Publish in 5 hrs',
'Publish in 3 hrs',
'Publish in 1 hr',
'Publish now'
];
Change your dropdownbutton like that:
DropdownButton<String>(
value: dropdownvalue,
icon: Icon(Icons.arrow_forward_ios),
items: items.map((String items) {
return DropdownMenuItem<String>(
value: items, child: Text(items));
}).toList(),
onChanged: (value) {
setState(() {
dropdownvalue = "value";
});
},
)
You need to declare your type of data in your dropdown.