int _code;
  String _description;
  String _unit;
  int _price;

  Products(this._code, this._description, this._unit, this._price);

 factory Products.fromJSON(Map<String, dynamic> json) {
   if (json == null) {
     return null;
   } else {
     return Products(json['code'], json['description'], json['unit'],json['price']);
   }
 }
}

Here is my code i cant return the null because of an error. i coudnt get what the error was. please help how to re arrange this without error. explain further would be fine. thanks in advance


Solution 1: Juan Carlos Ramón Condezo

Prefer factories that do not return null.

class Products {
  int _code;
  String _description;
  String _unit;
  int _price;

  Products(this._code, this._description, this._unit, this._price);

  factory Products.fromJSON(Map<String, dynamic> json) {
    return Products(
      json['code'],
      json['description'],
      json['unit'],
      json['price'],
    );
  }
}

But if you still want to verify if json is null, prefer a static method

class Products {
  int _code;
  String _description;
  String _unit;
  int _price;

  Products(this._code, this._description, this._unit, this._price);

  static Products? fromJSON(Map<String, dynamic>? json) {
   if (json == null) {
     return null;
   } else {
     return Products(json['code'], json['description'], json['unit'],json['price']);
   }
 }
}

The ? indicates that a Type can be null.