-
Notifications
You must be signed in to change notification settings - Fork 213
Allow functions as enum Constructor Parameter #2241
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
This would allow function literals in a constant scope. That sounds like #1048. |
Just to add that it is possible to pass functions in enums constructors, as long as they are constant. Example: enum Element {
dot("/assets/dot.png", isDotShown),
slash("/assets/slash.png", isSlashShown),
plus("/assets/plus.png", isPlusShown),
minus("/assets/minus.png", isMinusShown);
final String assetPath;
final bool Function(SharedPrefsProvider) _isShownFunction;
const Element(this.assetPath, this._isShownFunction);
bool isShown(SharedPrefsProvider sp){
return _isShownFunction(sp);
}
static bool isDotShown(SharedPrefsProvider sp) => sp.isDotShown;
static bool isSlashShown(SharedPrefsProvider sp) => sp.isSlashShown;
static bool isPlusShown(SharedPrefsProvider sp) => sp.isPlusShown;
static bool isMinusShown(SharedPrefsProvider sp) => sp.isMinusShown;
} However, this is not any better than an extension. |
I would guess that this is more easily optimized than the extension, but that is only a guess :). |
Why not move the logic to enum Element {
dot("/assets/dot.png"),
slash("/assets/slash.png"),
plus("/assets/plus.png"),
minus("/assets/minus.png");
final String assetPath;
const Element(this.assetPath);
}
class SharedPrefsProvider {
bool isShown(Element element) => prefs.getBool(element.path);
}
void main() {
final sp = SharedPrefsProvider();
final element = Element.plus;
print("Is shown? ${sp.isShown(element)}");
} If you don't have access to that class, you can simply make |
@Levi-Lesches This is a nice idea. That is a good solution for my example, but i think the general possibility to add a (constant) function to an enum would still be great. And the example of @mateusfccp shows that its possible, but not in a direct way. Maybe the solution could be to add a static inside the consturctor. like:
Thanks for all the suggestions. |
Closing this because it sounds like the specific request is already covered by #1048 and a good workaround was provided. |
I have an enum representing a bunch of elements that are clickable by the user.
Every possible element is a value in this enum.
Via SharedPreferences the user can toggle if he want to see this element or not.
To solve this problem i had to make an extension for my enum.
It would be nice to get this via constructor like this:
(The same for setting the value.)
The text was updated successfully, but these errors were encountered: