Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parameter issue on Dart

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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});
}       
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading