Since Dart 2.17 has been released you can now extend Enum class.
The trick is to assign a fixed/immutable value (int, string, whatever you prefer) used as the json representation.
enum Color {
/// The [jsonValue] must not change in time!
red(10), // Can be numbers
blue(20),
green("myGreen"), // Can be strings as well
gray(40),
yellow(50);
final dynamic jsonValue;
const Color(this.jsonValue);
static Color fromValue(jsonValue) =>
Color.values.singleWhere((i) => jsonValue == i.jsonValue);
}
main() {
var myValue = Color.green.jsonValue;
var myEnum = Color.fromValue(myValue);
print(myEnum);
}
This concept and much more is already implemented within my new jsonize 1.4.0 package which allows to easily serialize Enums, DateTime and any of your own classes.
This is a simple enum example:
import 'package:jsonize/jsonize.dart';
enum Color with JsonizableEnum {
red("rd"),
blue("bl"),
green("grn"),
gray("gry"),
yellow("yl");
@override
final dynamic jsonValue;
const Color(this.jsonValue);
}
void main() {
// Register your enum
Jsonize.registerEnum(Color.values);
Map<String, dynamic> myMap = {
"my_num": 1,
"my_str": "Hello!",
"my_color": Color.green,
};
var jsonRep = Jsonize.toJson(myMap);
var hereIsMyMap = Jsonize.fromJson(jsonRep);
print(hereIsMyMap);
}
This is an extended example on jsonize capabilities:
import 'package:jsonize/jsonize.dart';
enum Color with JsonizableEnum {
red("rd"),
blue("bl"),
green("grn"),
gray("gry"),
yellow("yl");
@override
final dynamic jsonValue;
const Color(this.jsonValue);
}
class MyClass implements Jsonizable<MyClass> {
String? str;
MyClass([this.str]);
factory MyClass.empty() => MyClass();
// Jsonizable implementation
@override
String get jsonClassCode => "mc";
@override
dynamic toJson() => str;
@override
MyClass? fromJson(value) => MyClass(value);
}
void main() {
// Register enums and classes
Jsonize.registerEnum(Color.values);
Jsonize.registerClass(MyClass.empty());
Map<String, dynamic> myMap = {
"my_num": 1,
"my_str": "Hello!",
"my_color": Color.green,
"my_dt": DateTime.now(),
"my_class": MyClass("here I am!")
};
var jsonRep = Jsonize.toJson(myMap);
var hereIsMyMap = Jsonize.fromJson(jsonRep);
print(hereIsMyMap);
}