Is it possible to bind a dropdownbutton to an enum? I have created an enum and trying to bind it to a dropdownbutton, see code below. Thanks for any help on this.
enum ClassType {
Class-A,
Class-B,
Class-C,
Class-D
}
DropdownButton<String>(
value: classType,
onChanged: (String newValue) {
setState(() {
viewModel.classType = newValue;
});
},
items: ClassType.map((String classType) {
return DropdownMenuItem<String>(
value: classType,
child: Text(classType),
);
}).toList(),
)
First, you need to update your DropdownButton type argument to ClassType
and not String
. In Dart, an enum declaration creates a new type, not Strings.
DropdownButton(...);
Next, you need to change the enum names. An enum has to be a valid dart identifier, meaning it can't contain the symbol -
.
enum ClassType {A, B, C, D}
I've also updated your map
method, there is not static iterator on your enum instance, you have to list them out. Also, you will need to convert them to Strings manually, either by calling toString
which will give you "ClassType.A"
, ClassType.B"
or by writing your own function to do this.
return DropdownButton<ClassType>(
value: classType,
onChanged: (ClassType newValue) {
setState(() {
viewModel.classType = newValue;
});
},
items: ClassType.values.map((ClassType classType) {
return DropdownMenuItem<ClassType>(
value: classType,
child: Text(classType.toString()));
}).toList();
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With