Home > Back-end >  Parameter issue on Dart
Parameter issue on Dart

Time:04-16

can somebody explain why

class SaveGlove {
final String serialNumber;
final String productionDate;

SaveGlove(this.serialNumber, this.productionDate);

SaveGlove.fromJson(Map<String, Object?> json)
    : this(
      serialNumber: json['serialNumber']! as String,
      productionDate: json['prductionDate']! as String,
    );

Map<String, Object?> toJson() {
return {
  'serialNumber': serialNumber,
  'prductionDate': productionDate,
};
}
}

doesn't work but when I change parameter in constructor like that:

  SaveGlove({required this.serialNumber, required this.productionDate});

it works?

CodePudding user response:

It is because Null Safety is added in Dart. In simple words, Null Safety means a variable cannot contain a ‘null’ value unless you initialized with null to that variable. All the runtime null-dereference errors will now be shown in compile time with null safety. So as you are initializing variables serialNumber & productionDate you have two options:

  1. Either make it compulsory to provide those variables values from constructor by adding required keyword.
class SaveGlove{
    String serialNumber;

    final String productionDate;
    
    SaveGlove({required this.serialNumber, required this.productionDate});
    
}       
  1. Or declare those variables as nullable, i.e which can accept null values. So you don't need the required keyword:
    
class SaveGlove{
    String? serialNumber;
    String? productionDate;
        
    SaveGlove({this.serialNumber,this.productionDate});
}       
  •  Tags:  
  • dart
  • Related