I had the need to serialize a theme setting class using Color for theme color and bool for light/dark theme.
Since Color is not serializable, I wrote a custom mapper that transforms a Color into an int (using color.value) and an int into a Color using Color(intValue).
Everything works fine and the class is serialized and deserialized correctly.
But, there is one problem:
final settings1 = ThemeSettings(Colors.pink, true);
final json = settings.toJson(); // {"color": 4294902374, "useDarkTheme": true}
final settings2 = ThemeSettings.fromJson(json);
print(settings1 == settings2); // returns false
This happens because settings1.color is a MaterialColor (which is inherited from Color), but, due the custom mapper converting an int into a Color, settings2.color is a Color.
The equality check tryes to compare Colors.pink as MaterialColor with Color(4294902374) and hence returns false here.
It would be nice if the equality checker consider the custom mapper to make its comparisons. In this case, it would compare 4294902374 with 4294902374 and correctly return true in the equality check.
I had the need to serialize a theme setting class using
Color
for theme color andbool
for light/dark theme.Since
Color
is not serializable, I wrote a custom mapper that transforms aColor
into anint
(usingcolor.value
) and anint
into aColor
usingColor(intValue)
.Everything works fine and the class is serialized and deserialized correctly.
But, there is one problem:
This happens because
settings1.color
is aMaterialColor
(which is inherited fromColor
), but, due the custom mapper converting anint
into aColor
,settings2.color
is aColor
.The equality check tryes to compare
Colors.pink as MaterialColor
withColor(4294902374)
and hence returns false here.It would be nice if the equality checker consider the custom mapper to make its comparisons. In this case, it would compare
4294902374
with4294902374
and correctly returntrue
in the equality check.