Last active
July 2, 2020 21:24
-
-
Save benoitjadinon/8509c23eaf07054db8935bdec87fab1c to your computer and use it in GitHub Desktop.
Dart enum to and from string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Copyright (C) 2012 Sergey Akopkokhyants. All Rights Reserved. | |
//Author: akserg | |
/// Emulation of Java Enum class. | |
/// | |
/// Example: | |
/// | |
/// class Meter<int> extends Enum<int> { | |
/// | |
/// const Meter(int val) : super (val); | |
/// | |
/// static const Meter HIGH = const Meter(100); | |
/// static const Meter MIDDLE = const Meter(50); | |
/// static const Meter LOW = const Meter(10); | |
/// } | |
/// | |
/// and usage: | |
/// | |
/// assert (Meter.HIGH, 100); | |
/// assert (Meter.HIGH is Meter); | |
abstract class Enum<T> { | |
final T _value; | |
const Enum(this._value); | |
T get value => _value; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'enum.dart'; | |
class EnumUtils { | |
/// EnumUtils.nameToString(Sizes.big) // 'big' | |
/// EnumUtils.nameToString(null, () => '-') // '-' | |
static String toNameString<T>(T enumValue, {String Function() orElse}) { | |
if (enumValue is Enum<String>) { | |
return enumValue.value; | |
} | |
var str = enumValue?.toString() ?? (orElse != null ? orElse() : null); | |
if (str?.contains('.') ?? false) return str?.split('.')?.last; | |
return str; | |
} | |
/// EnumUtils.fromName(Sizes.values, 'big') | |
/// EnumUtils.fromName(Sizes.values, 'small', or: Sizes.small) | |
/// EnumUtils.fromName(Sizes.values, 'medium', orElse: (name, values) => values.first()) | |
static T fromNameString<T>(List<T> enumValues, String name, {T Function(String name, List<T> values) orElse, T or}) { | |
return enumValues.firstWhere((enumItem) { | |
return enumItem.toString()?.split('.')?.last == name; | |
}, orElse: () => | |
orElse != null | |
? orElse(name, enumValues) | |
: or | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment