schultek/dart_mappable

CustomMapper breaks equality check when inheritance is used

Closed this issue · 2 comments

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.

You can implement the 'equals' method in the custom mapper.

Thanks, didn't read the documentation until the bottom, where this feature is.

Thanks for the amazing lib.