How can I add a support of for Custom Types within Objectbox?
Example:
class ShopListData {
int id;
int amount;
bool done;
ProductData productData;
ShopListData(
{required this.id,
required this.amount,
required this.done,
required this.productData});
}
class ProductData {
String? name;
String? brand;
String? ingredients;
String? quantity;
ProductData({
this.name,
this.brand,
this.ingredients,
this.quantity,
});
}
Where I get the error:
cannot use the default constructor of 'ShopListData': don't know how to initialize param productData - no such property.
I found out that one possible solution is to use relations, but since I have always 1:1 relation I think I don't need that option.
Instead I would like to store data as defined by ShopListData Class within the database. I read the custom type documentation. However I don't understand what is needed to add support/converter for the ProductData type. Who has an idea and could provide an example of how to add such support/converter?
I've edited your code like this:
@Entity()
class ShopListData {
int id;
int amount;
bool done;
ProductData productData;
ShopListData({required this.id, required this.amount, required this.done, required this.productData});
String get dbProductData => jsonEncode(productData.toJson());
set dbProductData(String value) => productData = ProductData.fromJson(jsonDecode(value));
}
@Entity()
@JsonSerializable()
class ProductData {
String? name;
String? brand;
String? ingredients;
String? quantity;
ProductData({this.name, this.brand, this.ingredients, this.quantity});
Map<String, dynamic> toJson() => _$ProductDataToJson(this);
factory ProductData.fromJson(Map<String, dynamic> json) => _$ProductDataFromJson(json);
}
Since ProductData
is a custom type for objectbox and should be mapped into a primitive type, I preferred stroring your ProductData
model as a String
in objectbox and converting it to a model again once it is taken form the db.
Ref: https://docs.objectbox.io/advanced/custom-types#convert-annotation-and-property-converter