Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DART - can I cast a string to an enum?

Tags:

enums

dart

Is there a way to convert a string to an enum?

enum eCommand{fred, joe, harry}

eCommand theCommand= cast(eCommand, 'joe');??

I think I just have to search for the enum (eg loop).

cheers

Steve

like image 252
Lymp Avatar asked Dec 07 '15 12:12

Lymp


People also ask

Can you cast a string to an enum?

IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.

How do you convert string to enum in darts?

We've made a number of convenience additions to the enum APIs in the dart:core library (language issue #1511). You can now get the String value for each enum value using . name: enum MyEnum { one, two, three } void main() { print(MyEnum.one.name); // Prints "one". }

Can enum take string values?

The Java enum type provides a language-supported way to create and use constant values. By defining a finite set of values, the enum is more type safe than constant literal variables like String or int.

How do I cast to enum?

To convert a string to ENUM or int to ENUM constant we need to use Enum. Parse function. Here is a youtube video https://www.youtube.com/watch?v=4nhx4VwdRDk which actually demonstrate's with string and the same applies for int.


1 Answers

Dart 2.6 introduces methods on enum types. It's much better to call a getter on the Topic or String itself to get the corresponding conversion via a named extension. I prefer this technique because I don't need to import a new package, saving memory and solving the problem with OOP.

I also get a compiler warning when I update the enum with more cases when I don't use default, since I am not handling the switch exhaustively.

Here's an example of that:

enum Topic { none, computing, general }

extension TopicString on String {
  Topic get topic {
    switch (this) {
      case 'computing':
        return Topic.computing;
      case 'general':
        return Topic.general;
      case 'none':
        return Topic.none;
    }
  }
}

extension TopicExtension on Topic {
  String get string {
    switch (this) {
      case Topic.computing:
        return 'computing';
      case Topic.general:
        return 'general';
      case Topic.none:
        return 'none';
    }
  }
}

This is really easy to use and understand, since I don't create any extra classes for conversion:

var topic = Topic.none;
final string = topic.string;
topic = string.topic;

(-:

like image 147
Pranav Kasetti Avatar answered Sep 17 '22 15:09

Pranav Kasetti