Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamic access the enum

Tags:

flutter

dart

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)

like image 223
mana Avatar asked Oct 12 '25 12:10

mana


1 Answers

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';
like image 63
Ivo Beckers Avatar answered Oct 16 '25 13:10

Ivo Beckers