-
Type: Improvement
-
Resolution: Unresolved
-
Priority: Major - P3
-
None
-
Affects Version/s: None
-
Component/s: None
-
?
-
0
-
1352
-
Needed
Problem
If the goal is to use realm model as app and local storage entity, then IMO it should be as close and flexible as dart data class models itself. So far the only way how to convert custom types to realm data type is by writing getter and setter. Not only it makes code less readable but also:
- have to duplicate same code in multiple RealmModels for Color property
- during object construction have to still pass colorAsInt
@RealmModel() class $Car { late String name; @MapTo('color') late int colorAsInt; Color get color => Color(colorAsInt); set color(Color c) => colorAsInt = c.value; }
Solution
https://pub.dev/packages/json_serializable provides good way of dealing with custom types.
@JsonSerializable() class Sample4 { Sample4(this.value); factory Sample4.fromJson(Map<String, dynamic> json) => _$Sample4FromJson(json); @EpochDateTimeConverter() final DateTime value; Map<String, dynamic> toJson() => _$Sample4ToJson(this); } class EpochDateTimeConverter implements JsonConverter<DateTime, int> { const EpochDateTimeConverter(); @override DateTime fromJson(int json) => DateTime.fromMillisecondsSinceEpoch(json); @override int toJson(DateTime object) => object.millisecondsSinceEpoch; }
It is using @EpochDateTimeConverter as custom data type converter, and then in Sample4 you can you desired DateTime type as value. In realm case it would look similar like this:
@RealmModel() class $Car { late String name; @ColorConverter late Color color; } class ColorConverter implements RealmConverter<Color, int> { const ColorConverter(); @override Color fromRealm(int val) => Color(val); @override int toRealm(Color object) => object.value; }
And this would deal with stated problems above:
- I takes now only 2 lines of code instead of 4
- I can create object with Car("Ford", Colors.white)
- I can reuse same ColorConverter in other RealmModels
ColorConverter and other common data converter types could be predefined, but also it adds even possibility to convert data with bigger complexity and annotate only in 2 lines of code.
Maybe this or similar feature is in near future, but I couldn't find it anywhere.
Alternatives
No response
How important is this improvement for you?
I would like to have it but have a workaround
Feature would mainly be used with
Local Database only