Bad state: ToOne relation field not initialized thrown when accessing target
giordy16 opened this issue · comments
Build info
- objectbox version: 2.2.1
- Flutter/Dart version: Flutter 3.16.8
- Build OS: macOS 14.1
- Deployment OS or device: Android 14
Problem
In my app I have a 3 layer architecture to represent objects: json, obox and domain. I want to update the Articles of my app through an API call. To parse the users that I receive from the server, I do: ArticleJson.fromJson(item).convertToObox().convertToDomain()
, where two converters are two extension function to create the object of the upper layer.
ArticleObox convertToObox() {
ArticleObox obox = ArticleObox(
id: id,
articleNumber: articleNumber,
country: country,
name: name,
plu: plu,
reserveBoolean00: reserveBoolean00,
reserveBoolean01: reserveBoolean01,
reserveBoolean02: reserveBoolean02,
reserveDate00: convertDateTimeFromJson(reserveDate00),
reserveDate01: convertDateTimeFromJson(reserveDate01),
reserveVarchar00: reserveVarchar00,
reserveVarchar01: reserveVarchar01,
reserveVarchar02: reserveVarchar02);
obox.articleGroup.targetId = articleGroupId;
obox.state.targetId = stateId;
return obox;
}
Article convertToDomain() {
Article domain = Article(
id: id,
articleNumber: articleNumber,
country: country,
name: name,
plu: plu,
reserveBoolean00: reserveBoolean00,
reserveBoolean01: reserveBoolean01,
reserveBoolean02: reserveBoolean02,
reserveDate00: reserveDate00,
reserveDate01: reserveDate01,
reserveVarchar00: reserveVarchar00,
reserveVarchar01: reserveVarchar01,
reserveVarchar02: reserveVarchar02);
domain.articleGroup = articleGroup.target?.convertToDomain();
domain.state = state.target?.convertToDomain();
return domain;
}
My problem is that when I call convertToDomain(), Bad state: ToOne relation field not initialized. Make sure attach(store) is called before using this.
is thrown when I try to access articleGroup.target, and I don't really understand where should I call attach(store).
I overall need to to pass through the Obox level because on the JSON level I just have the foreign key of some properties, instead on the domain level I want to have the object it self, and on the Obox level I build this link.