Convert a String to enum value in Dart

Viewed 28

Let us say that I have an enum:

enum XYZ { addition, updation, remove}

and I have a result string that I get using fromJson method which returns addition, updation or remove

How do I write a function so that these values get converted into the enum values. Something like XYZ.json['result'] which should return me XYZ.addition or XYZ.updation and so on

Any help would be really appreciated.

1 Answers

You could do this

String yourString = 'addition';
XYZ? result = XYZ.values.firstWhereOrNull((e) => e.name == yourString);

Note that result can be null if the string doesn't match any of them. You could write this to fall back to XYZ.addition for example

XYZ result = XYZ.values.firstWhereOrNull((e) => e.name == yourString) ?? XYZ.addition;
Related