Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a single Flutter model for both isar database and JsonSerializable

I am trying to use a single model for both storing the data locally using Isar, and also for using with Retrofit for REST API requests.

But Isar requires all the Linked classes to be defined with the datatype IsarLink<MyClassName> where JsonSerializable requires them with MyClassName as the datatype.

@Collection()
@JsonSerializable()
class UserGroup {
  @JsonKey(ignore: true)
  Id localId = Isar.autoIncrement; // you can also use id = null to auto increment

  @ignore
  @JsonKey(name: "_id")
  String? id;

  String name;
  String description;

  @ignore
  Domain? domain;
  
  @ignore
  UserGroupPermissions permissions;

  @ignore
  Organization? organization;

  
  @JsonKey(ignore: true)
  IsarLink<Organization?> organization = IsarLink<Organization?>();

  UserGroup({
    this.id,
    required this.name,
    required this.description,
    this.domain,
    required this.permissions,
    this.organization,
  });

  factory UserGroup.fromJson(Map<String, dynamic> json) => _$UserGroupFromJson(json);
  Map<String, dynamic> toJson() => _$UserGroupToJson(this);
}

Other than defining two variables like IsarLink<MyClassName> localOrganization with @JsonKey(ignore: true) for Isar and MyClassName with @ignore for JsonSerializable is there any other way to use a single variable for working with both of them?

Having to define two variables almost everywhere to support both of the generators makes the code look really messy

like image 514
Jishnu Raj Avatar asked Apr 11 '26 06:04

Jishnu Raj


1 Answers

You have to implement your own JsonConverter to convert IsarLink<Organization?> to Map<String, dynamic> and vice versa

like image 142
Gombal Avatar answered Apr 16 '26 02:04

Gombal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!