'A value of type "Null" can't be return from the constructor
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:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Juan Carlos Ramón Condezo |
