Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind an enum to DropdownButton in Flutter?

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(),
)
like image 426
Edmand Looi Avatar asked Apr 23 '18 01:04

Edmand Looi


1 Answers

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();
);
like image 78
Jonah Williams Avatar answered Sep 19 '22 01:09

Jonah Williams