flutterobjectbox

Flutter: Seralize ObjectBox objects as fields of other ObjectBox objects


consider the following ObjectBox classes:

@Entity()
class TestModel1 {
  @Id()
  int id;
  final TestModel2 testModel2; // un-seralizable

  TestModel1({this.id = 0, required this.testModel2,});
}



@Entity()
class TestModel2 {
  @Id()
  int id;
  final String test1;
  final int test2;

  TestModel1({this.id = 0, required this.test1, required this.test2});
}

My goal is to seralize TestModel2 inside another ObjectBox object (or any other custom class inside ObjectBox)

The Error I'm getting: Cannot use the default constructor of 'TestModel1': don't know how to initialize param testModel2 - no such property.

My question is whether there's an annotation I can use to allow me to seralize special types, or is converting to and from json is the only option?

Thanks for reading!


Solution

  • Either make the field a String and serialize to JSON as you said.

    Or, probably the better solution is to make the field a ToOne<TestModel2> relation.

    https://docs.objectbox.io/relations