Parameter issue on Dart

Viewed 32

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?

2 Answers

Your original code doesn't work because your constructor is declared to take two positional arguments,

SaveGlove(this.serialNumber, this.productionDate);

but you are calling it with named arguments:

    : this(
      serialNumber: json['serialNumber']! as String,
      productionDate: json['prductionDate']! as String,
    );

(This is a redirecting generative constructor, which tries to redirect to the SaveGlove constructor by passing it two named arguments.)

That doesn't work, positional parameters need positional arguments. If you had written the redirecting constructor as:

    : this(
      json['serialNumber']! as String,
      json['prductionDate']! as String,
    );

then it would have worked.

Changing the constructor to take two named parameters also makes the redirection be valid.

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});
}       
Related