Using a single Flutter model for both isar database and JsonSerializable
Asked Answered
C

1

11

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

Cacodemon answered 14/10, 2022 at 18:6 Comment(0)
B
1

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

Breebreech answered 28/2 at 11:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.