-
Notifications
You must be signed in to change notification settings - Fork 214
Add static parse method for Enums #1560
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Even with the helper plugin we have to write this:
When we ideally could just write something like:
The concrete downside to this are:
|
@esDotDev Hi, enum UserStatus { online, offline }
var userStatus = <UserStatus, String>{
UserStatus.online: "Online",
UserStatus.offline: "Offline",
};
String userStatusToString(UserStatus status) {
return userStatus[status];
// Another method.
// return userStatus.values.elementAt(status.index);
}
UserStatus userStatusFromString(String status) {
bool containsKey(UserStatus key) => userStatus[key].contains(status);
return userStatus.keys.firstWhere((containsKey));
}
// Status to String.
print(userStatusToString(UserStatus.online)); // -> Online
// Status from String.
print(userStatusFromString("Online")); // -> UserStatus.online
|
Ah nice approach. But still lots of boilerplate, and still not great for refactoring. If you change the name of If we had proper value enums, you could write that like this with absolutely no boilerplate and full refactoring support:
Or even:
But that is a bit off-topic maybe. |
I don't think a to/from string explictly are needed, but maybe enum values like Kotlin supports. https://kotlinlang.org/docs/enum-classes.html#implementing-interfaces-in-enum-classes They can represent arbitrary types of data without needing to be string specific. |
Right, that would be great, something like:
It would still be nice to have implicit support for string based values, so we don't need to write:
|
I see what you mean, and yes brining that feature over would be nice as well. |
Duplicate of dart-lang/sdk#33244 |
Closing since there is an existing issue for the same functionality. |
Uh oh!
There was an error while loading. Please reload this page.
Currently it's repetitive and verbose when trying to accomplish simple tasks with Enum.
For example, I might have
And I want to parse that into a query string so I have a link like "#/?menuType=search".
If we look at Kotlin, C# or Swift, they both support this in a straight forward way:
Swift:
Kotlin:
C#
To do this in a highly readable way in dart we need to write boilerplate code for each Enum (and usually import a plugin).
Parsing it the other way is something like:
Ideally, this would be built into the language and just be as simple as:
Adding
.name
addresses the toString use case (#1511) but fromString / parse is still cumbersome.The text was updated successfully, but these errors were encountered: