skip to Main Content

I have an enum and I want to access to it dynamically. I’m not sure if it’s possible or not.

enum EventType {
  earthquake,
  flood,
  fire
}

var event = "fire";

var mytype = EventType.event

You see, what I’m trying to achieve. Is it possible to access the enum like that (using a variable like mytype)

2

Answers


  1. Try below code

    Your Enum:

    enum EventType {
      earthquake,
      flood,
      fire
    }
    

    Just print it:

    print( EventType.fire.name);
    

    Output: fire

    Other Way:

    void main() {
      const day = EventType.Fire;
      print(day.text);
    }
    
    enum EventType {
      Earthquake("earthquake"),
      Flood("flood"), 
      Fire("fire");
      
    
      const EventType(this.text);
      final String text;
    }
    
    Login or Signup to reply.
  2. You could add this to your enum

      static EventType? fromName(String? name) {
        return values
            .firstWhereOrNull((e) => e.name == name);
      }
    

    then this could work:

    var event = "fire";
    
    var mytype = EventType.fromName(event);
    

    Note, using firstWhereOrNull requires

    import 'package:collection/collection.dart';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search