Home > Software design >  How can a property take the default values defined in the constructor? I am using the factory method
How can a property take the default values defined in the constructor? I am using the factory method

Time:05-26

I have a class with non-nullable values whose default values I have defined in the constructor.

class AirConPreferences {
  bool allowOn;
  int lowerTemperature;
  int upperTemperature;
  String nickName;
  AirConPreferences({
    this.allowOn = false,
    this.lowerTemperature = 19,
    this.upperTemperature = 24,
    this.nickName = "",
  });

  factory AirConPreferences.fromJson(Map<String, dynamic> json) =>
      AirConPreferences(
        allowOn: json['allowOn'],
        lowerTemperature: json['lowerTemperature'],
        upperTemperature: json['upperTemperature'],
        nickName: json['nickName'],
      );
  Map<String, dynamic> toJson() => {
        "allowOn": allowOn,
        "lowerTemperature": lowerTemperature,
        "upperTemperature": upperTemperature,
        "nickName": nickName,
      };
}

In my API call, I sometimes don't get all the values so some of the values could be null. Instead of taking the default value defined in the constructor, it's giving the following error:

AirConPreferences preferences = AirConPreferences.fromJson({});

Uncaught Error: TypeError: null: type 'JSNull' is not a subtype of type 'bool'

CodePudding user response:

The first check did you decode the JSON when you send the data into the fromJson method perimeter.

Then use the null check operator and set the default value. as like. ,

allowOn: json['allowOn']?? false

CodePudding user response:

You can do the following

AirConPreferences({
    final bool? allowOn,
    final int? lowerTemperature,
    final int? upperTemperature,
    final Stirng? nickName,
}) : this.allowOn = allowOn ?? false,
     this.lowerTemperature = lowerTemperature ?? 19,
     this.upperTemperature = upperTemperature ?? 24,
     this.nickName = nickName ?? "";

This will solve the issue, in case you will have multiple factories, you don't have to override them for all of them

  • Related