This project really hated me of coding,can anyone help me? What I’m doing wrong here? https://imgur.com/a/ptNwnCu
CodePudding user response:
The Source object which you are returning in Line 8 is expecting a type String for both id and name. You might not be getting a key named id
from the JSON, that's why the TypeError is coming.
You can add a null check operator to not get any exceptions.
return Source(id: json['id'] ?? "", name: json['name'] ?? "")
Now if the keys id
and name
do not exist in the JSON then an empty string will be returned.
CodePudding user response:
class Source {
Source({
this.id,
this.name,
});
String? id;
String name;
factory Source.fromJson(Map<String, dynamic> json) => Source(
id: json["id"] == null ? null : json["id"],
name: json["name"] == null ? null : json["name"],
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"name": name == null ? null : name,
};
}
You are missing the null check for the json data. Your class should look like above.