How to bind an enum to DropdownButton in Flutter?

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();
);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)