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
)
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With