flutterdartenumsmodel

Convert a String to enum value in Dart


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.


Solution

  • 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;
    

    firstWhereOrNull is part of the collection package so you would need to add that and import it like:

    import 'package:collection/collection.dart';