1

I'm writing a flutter app and i need to serialise a class to json. The class is :

@HiveType(typeId: 0)
@JsonSerializable()
class CartItem extends HiveObject {

  @HiveField(1)
  String item_id;

  @HiveField(2)
  String name;

  @HiveField(3)
  SelectionsList selections;

  @HiveField(4)
  String special_instructions;

  @HiveField(5)
  int quantity;

  @HiveField(6)
  double amount;

  @HiveField(7)
  @JsonKey(ignore: true)
  MenuItem item;

  CartItem(this.item_id, this.name, this.selections, this.quantity, this.special_instructions, this.amount, this.item);
}

however, due to the item field being ignored (intended), when i try to generate the .g.dart file, this error is thrown. Cannot populate the required constructor argument: item. It is assigned to an ignored field. I still need it to be in the constructor though, So is there a workaround for this?

weebkun
  • 29
  • 3

1 Answers1

0

So I managed to get this working. Not sure if it is the correct way but if it helps you out then great.

@HiveType(typeId: 0)
@JsonSerializable()
class CartItem extends HiveObject {

  ...

  @HiveField(7)
  @JsonKey(ignore: true)
  MenuItem item;

  CartItem(this.item_id, 
this.name, this.selections, this.quantity, this.special_instructions, this.amount, 
[this.item = MenuItem.empty()]);
}

You have to set the constructor entry an optional positional and give it a default value. You can also make it nullable and leave out the default on the constructor item.

  • Hey @Pieter van der Vyver, thank you for answering this question, Could you confirm, that you were able to generate the hive and json-methodes for this class. Because in my [stackoverflow thread](https://stackoverflow.com/questions/74290802/build-runner-failing-for-classes-extending-hiveobject) the build_runner fails to generate the methodes for the json-serializable. Would be a big help if you could confirm it worked for you in the past. – Donatic Nov 25 '22 at 18:01
  • 1
    Hi @Donatic. To be honest I cannot remember. Last December I had some free time between projects and I had this issue in a random project I was helping a friend out on. Best I can suggest is to give it a try. I am sure I tested this before posting it. – Pieter van der Vyver Nov 28 '22 at 08:14