flutterdart

How to set a default value for an object in json serialisable?


I want to set a default value for AvailableService. It straight forward enough with primitives. How would I do it with a custom Object

class Submenu extends Equatable {
     @JsonKey(defaultValue: "")
        final String name;
      @JsonKey(defaultValue: new AvailableService(false,false,false,false))
        final AvailableService availableService;
    
    }

the custom Object:

AvailableService {
bool supportsDelivery;
  bool supportsTableService;
  bool supportsCollection;
  bool supportsChat;
 
}

And the compile time error is

Arguments of a constant creation must be constant expressions.
Try making the argument a valid constant, or use 'new' to call the constructor

Solution

  • In general, as an annotation argument you can only pass constants, so you cannot pass an object created with new but only with a const constructor (you should define all AvailableService fields as final, and define a const constructor). In json_Serializable, however, defaultValue currently has some additional constraints:

    At the moment, therefore, until the aforementioned requests are followed up, the only workaround I have found is handle the defaultValue in the fromJson() factory:

      factory AvailableService.fromJson(Map<String, dynamic> json) =>
          json != null 
          ? _$AvailableServiceFromJson(json)
          : AvailableService(false, false, false, false);
    

    In short, JsonKey.defaultValue currently only supports literals -not even accepting constants- and can only be used for the default value of primitive type fields (or List, Map, Set).