schultek / dart_mappable

Improved json serialization and data classes with full support for generics, inheritance, customization and more.
https://pub.dev/packages/dart_mappable
MIT License
153 stars 23 forks source link

CustomMapper breaks equality check when inheritance is used #160

Closed JCKodel closed 9 months ago

JCKodel commented 9 months ago

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.

schultek commented 9 months ago

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

JCKodel commented 9 months ago

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

Thanks for the amazing lib.