Flutter json model error, _stackTrace = null - json

I got error in my json model when i parse my json, 'media' = null, but in api response 'media' has data and !=null, i think it is 'media' parsing error.Response work good too, statusCode=200, data is not empty too.How can i fix these errors?
this is my code:
class Product {
late final int id;
late final String name;
late final String categoryName;
late final List<Media> media;
Product({
required this.id,
required this.name,
required this.categoryName,
required this.media,
});
Product.fromJson(Map<String, dynamic> json){
id = json['id'];
name = json['name'];
categoryName = json['category_name'];
media = List.from(json['media']).map((e)=>Media.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['name'] = name;
_data['category_name'] = categoryName;
_data['media'] = media.map((e)=>e.toJson()).toList();
return _data;
}
}
class Media {
Media({
required this.id,
required this.productId,
required this.type,
required this.links,
this.position,
required this.createdAt,
required this.updatedAt,
});
late final int id;
late final int productId;
late final String type;
late final Links links;
String? position;
late final String createdAt;
late final String updatedAt;
Media.fromJson(Map<String, dynamic> json){
id = json['id'];
productId = json['product_id'];
type = json['type'];
links = Links.fromJson(json['links']);
position = json['position'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['product_id'] = productId;
_data['type'] = type;
_data['links'] = links.toJson();
_data['position'] = position;
_data['created_at'] = createdAt;
_data['updated_at'] = updatedAt;
return _data;
}
}
class Links {
Links({
required this.s3,
required this.cdn,
required this.local,
});
late final String? s3;
late final String? cdn;
late final Local local;
Links.fromJson(Map<String, dynamic> json){
s3 = json['s3'];
cdn = json['cdn'];
local = Local.fromJson(json['local']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['s3'] = s3;
_data['cdn'] = cdn;
_data['local'] = local.toJson();
return _data;
}
}
class Local {
Local({
required this.full,
required this.thumbnails,
});
late final String full;
late final Thumbnails thumbnails;
Local.fromJson(Map<String, dynamic> json){
full = json['full'];
thumbnails = Thumbnails.fromJson(json['thumbnails']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['full'] = full;
_data['thumbnails'] = thumbnails.toJson();
return _data;
}
}
class Thumbnails {
Thumbnails({
required this.s150,
required this.s350,
required this.s750,
});
late final String s150;
late final String s350;
late final String s750;
Thumbnails.fromJson(Map<String, dynamic> json){
s150 = json['150'];
s350 = json['350'];
s750 = json['750'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['150'] = s150;
_data['350'] = s350;
_data['750'] = s750;
return _data;
}
}
my errors:
type 'Null' is not a subtype of type 'Iterable'
_stackTrace = null

Trying making media nullable there I think it might serve you better.
final List<Media>? media;

Related

How to properly create instances containing a Map from a json file in dart?

I'm trying to deserialize a json file and create instances from it but whatever way I use, I end up stucked because of the dynamic type :
type '_Map<String, dynamic>' is not a subtype of type 'Map<String, int>'
Here's my model :
class Race {
final String name;
final Map<String, int> abilitiesUpdater;
const Race({
required this.name,
required this.abilitiesUpdater
});
static fromJson(json) => Race(name: json['name'], abilitiesUpdater: json['abilitiesUpdater']);
}
Here's how I'm trying to deserialize the json file :
class RacesApi {
static Future<List<Race>> getRacesLocally(BuildContext context) async {
final assetBundle = DefaultAssetBundle.of(context);
final String fileContent = await assetBundle.loadString('Assets/COC_Monstres/Races.json');
List<dynamic> parsedListJson = jsonDecode(fileContent);
List<Race> racesList = List<Race>.from(parsedListJson.map<Race>((dynamic i) => Race.fromJson(i)));
return racesList;
}
}
Here's my json file :
[
{
"name": "Vampire",
"abilitiesUpdater": {
"DEX": 2,
"CHA": 2
}
},
{
"name": "Créature du lagon",
"abilitiesUpdater": {
"FOR": 2,
"CON": 2
}
},
...
]
How can I properly cast this json object to fit into my class ?
This works:
class Race {
final String name;
// changed to dynamic
final Map<String, dynamic> abilitiesUpdater;
const Race({required this.name, required this.abilitiesUpdater});
static fromJson(json) =>
Race(name: json['name'], abilitiesUpdater: json['abilitiesUpdater']);
}
Maybe after get the object you can parse that dynamic into int if you need it.
Change your Model Class to this:
class Race {
Race({
required this.name,
required this.abilitiesUpdater,
});
late final String name;
late final AbilitiesUpdater abilitiesUpdater;
Race.fromJson(Map<String, dynamic> json){
name = json['name'];
abilitiesUpdater = AbilitiesUpdater.fromJson(json['abilitiesUpdater']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['name'] = name;
_data['abilitiesUpdater'] = abilitiesUpdater.toJson();
return _data;
}
}
class AbilitiesUpdater {
AbilitiesUpdater({
required this.FOR,
required this.CON,
});
late final int FOR;
late final int CON;
AbilitiesUpdater.fromJson(Map<String, dynamic> json){
FOR = json['FOR'];
CON = json['CON'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['FOR'] = FOR;
_data['CON'] = CON;
return _data;
}
}
you can cast the json['abilitiesUpdater'] as Map<String, int> because internally flutter will set it default as Map<String, dynamic>
Code
class Race {
final String name;
final Map<String, int> abilitiesUpdater;
const Race({
required this.name,
required this.abilitiesUpdater
});
static fromJson(json) => Race(name: json['name'], abilitiesUpdater: json['abilitiesUpdater']) as Map<String,int>;
}
it is working fine with me i tried it here is the link to the code https://dartpad.dev/?id=550918b56987552eb3d631ce8cb9e063.
If you still getting error you can try this
class Race {
final String name;
final Map<String, int> abilitiesUpdater;
Race({
required this.name,
required this.abilitiesUpdater
});
static fromJson(json) => Race(name: json['name'], abilitiesUpdater: (json['abilitiesUpdater']as Map<String,int>)) ;
}
or you can try this
class Race {
final String name;
final Map<String, int> abilitiesUpdater;
const Race({required this.name, required this.abilitiesUpdater});
static fromJson(json) => Race(
name: json['name'],
abilitiesUpdater: json['abilitiesUpdater']
.map((key, value) => MapEntry<String, int>(key, value as int)),
);
}
Edit : To have something a little bit more handy and scalable, I created an extension, and it works fine eventhough I have to cast twice the object...
My model :
// import my extension
class Race {
Race({
required this.name,
required this.abilitiesUpdater,
});
late final String name;
late final Map<String, int> abilitiesUpdater;
// late final AbilitiesUpdater abilitiesUpdater;
Race.fromJson(Map<String, dynamic> json){
name = json['name'];
abilitiesUpdater = (json['abilitiesUpdater'] as Map<String, dynamic>).parseToStringInt();
}
}
My extension :
extension Casting on Map<String, dynamic> {
Map<String, int> parseToStringInt() {
final Map<String, int> map = {};
forEach((key, value) {
int? testInt = int.tryParse(value.toString());
if (testInt != null) {
map[key] = testInt;
} else {
debugPrint("$value can't be parsed to int");
}
});
return map;
}
}
Once again, any help on cleaning this is appreciated !
Original answer :
Thanks to Sanket Patel's answer, I ended up with a few changes that made my code works. However I'm pretty clueless on why I can't directly cast a
Map<String, dynamic>
object into a
Map<String, int>
one.
Any info on this would be appreciated :)
Here's how I changed my model class in the end :
class Race {
Race({
required this.name,
required this.abilitiesUpdater,
});
late final String name;
late final AbilitiesUpdater abilitiesUpdater;
Race.fromJson(Map<String, dynamic> json){
name = json['name'];
abilitiesUpdater = AbilitiesUpdater.fromJson(json['abilitiesUpdater']);
}
}
class AbilitiesUpdater {
final Map<String, int> abilitiesUpdater = {};
AbilitiesUpdater.fromJson(Map<String, dynamic> json){
json.forEach((key, value) {
abilitiesUpdater[key] = int.parse(value.toString());
});
}
}

Flutter nested json parsing error, 'Model' can't be assigned to the parameter type 'Map<String, dynamic>'

When i'm parsing my nested json, my media class in my model can be null, I can't check it for null, and i cant map my nested elements
there is my model :
class Product {
Product({
required this.id,
required this.name,
required this.categoryName,
this.media,
});
late final int id;
late final String name;
late final String categoryName;
List<Media>? media;
Product.fromJson(Map<String, dynamic> json){
id = json['id'];
name = json['name'];
categoryName = json['category_name'];
media != null ? (json["media"] as List).map((a) => Media.fromJson(a)).toList() : null;
// media != null ? List.from(json['media']).map((e)=>Media.fromJson(e)).toList() : null;
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['id'] = id;
data['name'] = name;
data['category_name'] = categoryName;
data['media'] = media!.map((e)=>e.toJson()).toList();
return data;
}
}
class Media {
Media({
required this.id,
required this.productId,
required this.type,
required this.links,
});
late final int id;
late final int productId;
late final String type;
late final Links links;
Media.fromJson(Map<String, dynamic> json){
id = json['id'];
productId = json['product_id'];
type = json['type'];
links = Links.fromJson(json['links']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['product_id'] = productId;
_data['type'] = type;
_data['links'] = links.toJson();
return _data;
}
}
when i try to loop it with forEach i got:
error: The argument type 'Media' can't be assigned to the parameter type 'Map<String, dynamic>'. (argument_type_not_assignable at [yiwumart] lib/catalog_screens/catalog_item.dart:72)
final media = productItem.media!.map((e) => Media.fromJson(e)).toList();
Try
Product.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
categoryName = json['category_name'];
media = (json["media"] as List?)?.map((a) => Media.fromJson(a)).toList();
}

can someone help me with this Complex json to dart

i get a json response from this link https://itunes.apple.com/in/rss/topalbums/limit=25/json
can anyone make a model class where i can so a http get request and use the snapshot data in future builder . I tried quicktype but the model class throwing errors like null is not a subtype of string
Yes. It's always a good practice to convert the JSON in Models and use it in the code.
class AppleModel {
Feed? feed;
AppleModel({this.feed});
AppleModel.fromJson(Map<String, dynamic> json) {
feed = json['feed'] != null ? new Feed.fromJson(json['feed']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.feed != null) {
data['feed'] = this.feed!.toJson();
}
return data;
}
}
class Feed {
Author? author;
Entry? entry;
Name? updated;
Name? rights;
Name? title;
Name? icon;
List<Link>? link;
Name? id;
Feed(
{this.author,
this.entry,
this.updated,
this.rights,
this.title,
this.icon,
this.link,
this.id});
Feed.fromJson(Map<String, dynamic> json) {
author =
json['author'] != null ? new Author.fromJson(json['author']) : null;
entry = json['entry'] != null ? new Entry.fromJson(json['entry']) : null;
updated =
json['updated'] != null ? new Name.fromJson(json['updated']) : null;
rights = json['rights'] != null ? new Name.fromJson(json['rights']) : null;
title = json['title'] != null ? new Name.fromJson(json['title']) : null;
icon = json['icon'] != null ? new Name.fromJson(json['icon']) : null;
if (json['link'] != null) {
link = <Link>[];
json['link'].forEach((v) {
link!.add(new Link.fromJson(v));
});
}
id = json['id'] != null ? new Name.fromJson(json['id']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.author != null) {
data['author'] = this.author!.toJson();
}
if (this.entry != null) {
data['entry'] = this.entry!.toJson();
}
if (this.updated != null) {
data['updated'] = this.updated!.toJson();
}
if (this.rights != null) {
data['rights'] = this.rights!.toJson();
}
if (this.title != null) {
data['title'] = this.title!.toJson();
}
if (this.icon != null) {
data['icon'] = this.icon!.toJson();
}
if (this.link != null) {
data['link'] = this.link!.map((v) => v.toJson()).toList();
}
if (this.id != null) {
data['id'] = this.id!.toJson();
}
return data;
}
}
class Author {
Name? name;
Name? uri;
Author({this.name, this.uri});
Author.fromJson(Map<String, dynamic> json) {
name = json['name'] != null ? new Name.fromJson(json['name']) : null;
uri = json['uri'] != null ? new Name.fromJson(json['uri']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.name != null) {
data['name'] = this.name!.toJson();
}
if (this.uri != null) {
data['uri'] = this.uri!.toJson();
}
return data;
}
}
class Name {
String? label;
Name({this.label});
Name.fromJson(Map<String, dynamic> json) {
label = json['label'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['label'] = this.label;
return data;
}
}
class Entry {
Name? imName;
List<ImImage>? imImage;
Name? imItemCount;
ImImage? imPrice;
ImContentType? imContentType;
Name? rights;
Name? title;
ImContentType? link;
Name? id;
ImImage? imArtist;
ImContentType? category;
ImImage? imReleaseDate;
Entry(
{this.imName,
this.imImage,
this.imItemCount,
this.imPrice,
this.imContentType,
this.rights,
this.title,
this.link,
this.id,
this.imArtist,
this.category,
this.imReleaseDate});
Entry.fromJson(Map<String, dynamic> json) {
imName =
json['im:name'] != null ? new Name.fromJson(json['im:name']) : null;
if (json['im:image'] != null) {
imImage = <ImImage>[];
json['im:image'].forEach((v) {
imImage!.add(new ImImage.fromJson(v));
});
}
imItemCount = json['im:itemCount'] != null
? new Name.fromJson(json['im:itemCount'])
: null;
imPrice = json['im:price'] != null
? new ImImage.fromJson(json['im:price'])
: null;
imContentType = json['im:contentType'] != null
? new ImContentType.fromJson(json['im:contentType'])
: null;
rights = json['rights'] != null ? new Name.fromJson(json['rights']) : null;
title = json['title'] != null ? new Name.fromJson(json['title']) : null;
link =
json['link'] != null ? new ImContentType.fromJson(json['link']) : null;
id = json['id'] != null ? new Name.fromJson(json['id']) : null;
imArtist = json['im:artist'] != null
? new ImImage.fromJson(json['im:artist'])
: null;
category = json['category'] != null
? new ImContentType.fromJson(json['category'])
: null;
imReleaseDate = json['im:releaseDate'] != null
? new ImImage.fromJson(json['im:releaseDate'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.imName != null) {
data['im:name'] = this.imName!.toJson();
}
if (this.imImage != null) {
data['im:image'] = this.imImage!.map((v) => v.toJson()).toList();
}
if (this.imItemCount != null) {
data['im:itemCount'] = this.imItemCount!.toJson();
}
if (this.imPrice != null) {
data['im:price'] = this.imPrice!.toJson();
}
if (this.imContentType != null) {
data['im:contentType'] = this.imContentType!.toJson();
}
if (this.rights != null) {
data['rights'] = this.rights!.toJson();
}
if (this.title != null) {
data['title'] = this.title!.toJson();
}
if (this.link != null) {
data['link'] = this.link!.toJson();
}
if (this.id != null) {
data['id'] = this.id!.toJson();
}
if (this.imArtist != null) {
data['im:artist'] = this.imArtist!.toJson();
}
if (this.category != null) {
data['category'] = this.category!.toJson();
}
if (this.imReleaseDate != null) {
data['im:releaseDate'] = this.imReleaseDate!.toJson();
}
return data;
}
}
class ImImage {
String? label;
Attributes? attributes;
ImImage({this.label, this.attributes});
ImImage.fromJson(Map<String, dynamic> json) {
label = json['label'];
attributes = json['attributes'] != null
? new Attributes.fromJson(json['attributes'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['label'] = this.label;
if (this.attributes != null) {
data['attributes'] = this.attributes!.toJson();
}
return data;
}
}
class Attributes {
String? height;
Attributes({this.height});
Attributes.fromJson(Map<String, dynamic> json) {
height = json['height'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['height'] = this.height;
return data;
}
}
class Attributes {
String? amount;
String? currency;
Attributes({this.amount, this.currency});
Attributes.fromJson(Map<String, dynamic> json) {
amount = json['amount'];
currency = json['currency'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['amount'] = this.amount;
data['currency'] = this.currency;
return data;
}
}
class ImContentType {
ImContentType? imContentType;
Attributes? attributes;
ImContentType({this.imContentType, this.attributes});
ImContentType.fromJson(Map<String, dynamic> json) {
imContentType = json['im:contentType'] != null
? new ImContentType.fromJson(json['im:contentType'])
: null;
attributes = json['attributes'] != null
? new Attributes.fromJson(json['attributes'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.imContentType != null) {
data['im:contentType'] = this.imContentType!.toJson();
}
if (this.attributes != null) {
data['attributes'] = this.attributes!.toJson();
}
return data;
}
}
class ImContentType {
Attributes? attributes;
ImContentType({this.attributes});
ImContentType.fromJson(Map<String, dynamic> json) {
attributes = json['attributes'] != null
? new Attributes.fromJson(json['attributes'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.attributes != null) {
data['attributes'] = this.attributes!.toJson();
}
return data;
}
}
class Attributes {
String? term;
String? label;
Attributes({this.term, this.label});
Attributes.fromJson(Map<String, dynamic> json) {
term = json['term'];
label = json['label'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['term'] = this.term;
data['label'] = this.label;
return data;
}
}
class Attributes {
String? rel;
String? type;
String? href;
Attributes({this.rel, this.type, this.href});
Attributes.fromJson(Map<String, dynamic> json) {
rel = json['rel'];
type = json['type'];
href = json['href'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['rel'] = this.rel;
data['type'] = this.type;
data['href'] = this.href;
return data;
}
}
class Attributes {
String? imId;
Attributes({this.imId});
Attributes.fromJson(Map<String, dynamic> json) {
imId = json['im:id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['im:id'] = this.imId;
return data;
}
}
class Attributes {
String? href;
Attributes({this.href});
Attributes.fromJson(Map<String, dynamic> json) {
href = json['href'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['href'] = this.href;
return data;
}
}
class Attributes {
String? imId;
String? term;
String? scheme;
String? label;
Attributes({this.imId, this.term, this.scheme, this.label});
Attributes.fromJson(Map<String, dynamic> json) {
imId = json['im:id'];
term = json['term'];
scheme = json['scheme'];
label = json['label'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['im:id'] = this.imId;
data['term'] = this.term;
data['scheme'] = this.scheme;
data['label'] = this.label;
return data;
}
}
Moreover, You can use this github.io to convert it into Dart Objects. Please feel free to make changes to above Attributes model as you require in some other way.
This is quite a big json file. If you're only interested in parts of it you don't have to parse every object. Instead, use deep_pick to pick the values you need.
This example parses multiple albums
import 'package:http/http.dart' as http;
import 'package:deep_pick/deep_pick.dart';
Future<void> main() async {
final response = await http.get(Uri.parse('https://itunes.apple.com/in/rss/topalbums/limit=10/json'));
final albums = pickFromJson(response.body, 'feed', 'entry').asListOrEmpty((pick) => Album.fromPick(pick));
print(albums);
}
class Album {
final Uri? link;
final String? name;
final String? artist;
final DateTime? releaseDate;
factory Album.fromPick(Pick pick) {
return Album(
link: pick('link', 0, 'attributes', 'href').letOrNull((it) => Uri.parse(it.asStringOrThrow())),
name: pick('im:name').asStringOrNull(),
artist: pick('im:artist', 'label').asStringOrNull(),
releaseDate: pick('im:releaseDate', 'label').asDateTimeOrNull(),
);
}
const Album({
required this.link,
required this.name,
required this.artist,
required this.releaseDate,
});
#override
String toString() {
return 'Album{link: $link, name: $name, artist: $artist, releaseDate: $releaseDate}';
}
}
Here:
UPDATED MODEL
class Model {
Model({
required this.feed,
});
late final Feed feed;
Model.fromJson(Map<String, dynamic> json) {
feed = Feed.fromJson(json['feed']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['feed'] = feed.toJson();
return _data;
}
}
class Feed {
Feed({
required this.author,
required this.entry,
required this.updated,
required this.rights,
required this.title,
required this.icon,
required this.link,
required this.id,
});
late final Author author;
late final List<Entry> entry;
late final Updated updated;
late final Rights rights;
late final Title title;
late final Icon icon;
late final List<Link> link;
late final Id id;
Feed.fromJson(Map<String, dynamic> json) {
author = Author.fromJson(json['author']);
entry = json['entry'] is Map ? [Entry.fromJson(Map.from(json['entry']))] : List.from(json['entry']).map((e) => Entry.fromJson(Map.from(e))).toList();
updated = Updated.fromJson(json['updated']);
rights = Rights.fromJson(json['rights']);
title = Title.fromJson(json['title']);
icon = Icon.fromJson(json['icon']);
link = List.from(json['link']).map((e) => Link.fromJson(e)).toList();
id = Id.fromJson(json['id']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['author'] = author.toJson();
_data['entry'] = entry.toString();
_data['updated'] = updated.toJson();
_data['rights'] = rights.toJson();
_data['title'] = title.toJson();
_data['icon'] = icon.toJson();
_data['link'] = link.map((e) => e.toJson()).toList();
_data['id'] = id.toJson();
return _data;
}
}
class Author {
Author({
required this.name,
required this.uri,
});
late final Name name;
late final ModelUri uri;
Author.fromJson(Map<String, dynamic> json) {
name = Name.fromJson(json['name']);
uri = ModelUri.fromJson(json['uri']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['name'] = name.toJson();
_data['uri'] = uri.toJson();
return _data;
}
}
class Name {
Name({
required this.label,
});
late final String label;
Name.fromJson(Map<String, dynamic> json) {
label = json['label'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['label'] = label;
return _data;
}
}
class ModelUri {
ModelUri({
required this.label,
});
late final String label;
ModelUri.fromJson(Map<String, dynamic> json) {
label = json['label'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['label'] = label;
return _data;
}
}
class Entry {
Entry({
required this.imname,
required this.imimage,
required this.imitemCount,
required this.imprice,
required this.imcontentType,
required this.rights,
required this.title,
required this.link,
required this.id,
required this.imartist,
required this.category,
required this.imreleaseDate,
});
late final Imname imname;
late final List<Imimage> imimage;
late final ImitemCount imitemCount;
late final Imprice imprice;
late final ImcontentType imcontentType;
late final Rights rights;
late final Title title;
late final Link link;
late final Id id;
late final Imartist imartist;
late final Category category;
late final ImreleaseDate? imreleaseDate;
Entry.fromJson(Map<String, dynamic> json) {
imname = Imname.fromJson(json['im:name']);
imimage =
List.from(json['im:image']).map((e) => Imimage.fromJson(e)).toList();
imitemCount = ImitemCount.fromJson(json['im:itemCount']);
imprice = Imprice.fromJson(json['im:price']);
imcontentType = ImcontentType.fromJson(json['im:contentType']);
rights = Rights.fromJson(json['rights']);
title = Title.fromJson(json['title']);
link = Link.fromJson(json['link']);
id = Id.fromJson(json['id']);
imartist = Imartist.fromJson(json['im:artist']);
category = Category.fromJson(json['category']);
imreleaseDate = json['imreleaseDate'] == null
? null
: ImreleaseDate.fromJson(json['imreleaseDate']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['im:name'] = imname.toJson();
_data['im:image'] = imimage.map((e) => e.toJson()).toList();
_data['im:itemCount'] = imitemCount.toJson();
_data['im:price'] = imprice.toJson();
_data['im:contentType'] = imcontentType.toJson();
_data['rights'] = rights.toJson();
_data['title'] = title.toJson();
_data['link'] = link.toJson();
_data['id'] = id.toJson();
_data['im:artist'] = imartist.toJson();
_data['category'] = category.toJson();
_data['im:releaseDate'] = imreleaseDate?.toJson();
return _data;
}
}
class Imname {
Imname({
required this.label,
});
late final String label;
Imname.fromJson(Map<String, dynamic> json) {
label = json['label'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['label'] = label;
return _data;
}
}
class Imimage {
Imimage({
required this.label,
required this.attributes,
});
late final String label;
late final Attributes attributes;
Imimage.fromJson(Map<String, dynamic> json) {
label = json['label'];
attributes = Attributes.fromJson(json['attributes']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['label'] = label;
_data['attributes'] = attributes.toJson();
return _data;
}
}
class Attributes {
Attributes({
required this.height,
});
late final String? height;
Attributes.fromJson(Map<String, dynamic>? json) {
height = json?['height'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['height'] = height;
return _data;
}
}
class ImitemCount {
ImitemCount({
required this.label,
});
late final String label;
ImitemCount.fromJson(Map<String, dynamic> json) {
label = json['label'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['label'] = label;
return _data;
}
}
class Imprice {
Imprice({
required this.label,
required this.attributes,
});
late final String label;
late final Attributes attributes;
Imprice.fromJson(Map<String, dynamic> json) {
label = json['label'];
attributes = Attributes.fromJson(json['attributes']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['label'] = label;
_data['attributes'] = attributes.toJson();
return _data;
}
}
class ImcontentType {
ImcontentType({
required this.imcontentType,
required this.attributes,
});
late final ImcontentType? imcontentType;
late final Attributes attributes;
ImcontentType.fromJson(Map<String, dynamic> json) {
imcontentType = json['im:contentType'] == null
? null
: ImcontentType.fromJson(json['im:contentType']);
attributes = Attributes.fromJson(json['attributes']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['im:contentType'] = imcontentType?.toJson();
_data['attributes'] = attributes.toJson();
return _data;
}
}
class Rights {
Rights({
required this.label,
});
late final String label;
Rights.fromJson(Map<String, dynamic> json) {
label = json['label'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['label'] = label;
return _data;
}
}
class Title {
Title({
required this.label,
});
late final String label;
Title.fromJson(Map<String, dynamic> json) {
label = json['label'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['label'] = label;
return _data;
}
}
class Link {
Link({
required this.attributes,
});
late final Attributes attributes;
Link.fromJson(Map<String, dynamic> json) {
attributes = Attributes.fromJson(json['attributes']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['attributes'] = attributes.toJson();
return _data;
}
}
class Id {
Id({
required this.label,
required this.attributes,
});
late final String label;
late final Attributes? attributes;
Id.fromJson(Map<String, dynamic> json) {
label = json['label'];
attributes = json['attributes'] == null
? null
: Attributes.fromJson(json['attributes']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['label'] = label;
_data['attributes'] = attributes?.toJson();
return _data;
}
}
class Imartist {
Imartist({
required this.label,
required this.attributes,
});
late final String label;
late final Attributes? attributes;
Imartist.fromJson(Map<String, dynamic> json) {
print("attribute json: $json");
label = json['label'];
attributes = Attributes.fromJson(json['attributes']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['label'] = label;
_data['attributes'] = attributes?.toJson();
return _data;
}
}
class Category {
Category({
required this.attributes,
});
late final Attributes attributes;
Category.fromJson(Map<String, dynamic> json) {
attributes = Attributes.fromJson(json['attributes']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['attributes'] = attributes.toJson();
return _data;
}
}
class ImreleaseDate {
ImreleaseDate({
required this.label,
required this.attributes,
});
late final String label;
late final Attributes attributes;
ImreleaseDate.fromJson(Map<String, dynamic> json) {
label = json['label'];
attributes = Attributes.fromJson(json['attributes']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['label'] = label;
_data['attributes'] = attributes.toJson();
return _data;
}
}
class Updated {
Updated({
required this.label,
});
late final String label;
Updated.fromJson(Map<String, dynamic> json) {
label = json['label'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['label'] = label;
return _data;
}
}
class Icon {
Icon({
required this.label,
});
late final String label;
Icon.fromJson(Map<String, dynamic> json) {
label = json['label'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['label'] = label;
return _data;
}
}
API CALL
main() {
execute();
}
void execute() async {
Response response = await get(Uri.parse("https://itunes.apple.com/in/rss/topalbums/limit=1/json"));
print(response.body);
var x = Model.fromJson(jsonDecode(response.body));
print(x.feed.toJson());
}

What is the error in my code and how do I parse the data from a json successfully?

I am developing a weather app in flutter and encountered an issue where when we type in the city name in the search bar and click on the next icon it displays the weather of that particular place on the screen. But just to make sure that the data is being parsed properly, I'm only calling the data in the console. Though the code shows no errors, multiple errors are being thrown in the console. Could anyone please tell me how I can solve this error and parse this data successfully?
The error displayed in the console is given below:
An Observatory debugger and profiler on Chrome is available at: http://127.0.0.1:50548/vYt04KYoAA8=
The Flutter DevTools debugger and profiler on Chrome is available at:
http://127.0.0.1:9101?uri=http://127.0.0.1:50548/vYt04KYoAA8=
{"cod":"400","message":"Nothing to geocode"}
Error: Exception: Failed to get posts
at Object.throw_ [as throw] (http://localhost:50501/dart_sdk.js:5061:11)
at getWeather (http://localhost:50501/packages/finalproject/Weatherproj/data_service.dart.lib.js:31:21)
at getWeather.next (<anonymous>)
at http://localhost:50501/dart_sdk.js:38640:33
at _RootZone.runUnary (http://localhost:50501/dart_sdk.js:38511:59)
at _FutureListener.thenAwait.handleValue (http://localhost:50501/dart_sdk.js:33713:29)
at handleValueCallback (http://localhost:50501/dart_sdk.js:34265:49)
at Function._propagateToListeners (http://localhost:50501/dart_sdk.js:34303:17)
at _Future.new.[_completeWithValue] (http://localhost:50501/dart_sdk.js:34151:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:50501/dart_sdk.js:34172:35)
at Object._microtaskLoop (http://localhost:50501/dart_sdk.js:38778:13)
at _startMicrotaskLoop (http://localhost:50501/dart_sdk.js:38784:13)
at http://localhost:50501/dart_sdk.js:34519:9
Below is the code for the model class:
class WeatherAppDetails {
City? city;
String? cod;
double? message;
int? cnt;
List<ListDetails>? list;
WeatherAppDetails(
{required this.city,
required this.cod,
required this.message,
required this.cnt,
required this.list});
WeatherAppDetails.fromJson(Map<String, dynamic> json) {
final cod = json['cod'];
final message = json['message'];
final cnt = json['cnt'];
if (json['list'] != null) {
list = <ListDetails>[];
json['list'].forEach((v) {
list!.add(ListDetails.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
if (city != null) {
data['city'] = city!.toJson();
}
data['cod'] = cod;
data['message'] = message;
data['cnt'] = cnt;
if (list != null) {
data['list'] = list!.map((v) => v.toJson()).toList();
}
return data;
}
}
class City {
int? id;
String? name;
Coord? coord;
String? country;
int? population;
int? timezone;
City(
{required this.id,
required this.name,
required this.coord,
required this.country,
required this.population,
required this.timezone});
City.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
coord = (json['coord'] != null ? Coord.fromJson(json['coord']) : null)!;
country = json['country'];
population = json['population'];
timezone = json['timezone'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['id'] = id;
data['name'] = name;
if (coord != null) {
data['coord'] = coord!.toJson();
}
data['country'] = country;
data['population'] = population;
data['timezone'] = timezone;
return data;
}
}
class Coord {
double? lon;
double? lat;
Coord({required this.lon, required this.lat});
Coord.fromJson(Map<String, dynamic> json) {
lon = json['lon'];
lat = json['lat'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['lon'] = lon;
data['lat'] = lat;
return data;
}
}
class ListDetails {
int? dt;
int? sunrise;
int? sunset;
Temp? temp;
FeelsLike? feelsLike;
int? pressure;
int? humidity;
List<WeatherDetails>? weather;
double? speed;
int? deg;
double? gust;
int? clouds;
double? pop;
double? rain;
ListDetails(
{required this.dt,
required this.sunrise,
required this.sunset,
required this.temp,
required this.feelsLike,
required this.pressure,
required this.humidity,
required this.weather,
required this.speed,
required this.deg,
required this.gust,
required this.clouds,
required this.pop,
required this.rain});
ListDetails.fromJson(Map<String, dynamic> json) {
dt = json['dt'];
sunrise = json['sunrise'];
sunset = json['sunset'];
temp = json['temp'] != null ? Temp.fromJson(json['temp']) : null;
feelsLike = json['feels_like'] != null
? FeelsLike.fromJson(json['feels_like'])
: null;
pressure = json['pressure'];
humidity = json['humidity'];
if (json['weather'] != null) {
weather = <WeatherDetails>[];
json['weather'].forEach((v) {
weather!.add(WeatherDetails.fromJson(v));
});
}
speed = json['speed'];
deg = json['deg'];
gust = json['gust'];
clouds = json['clouds'];
pop = json['pop'];
rain = json['rain'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['dt'] = dt;
data['sunrise'] = sunrise;
data['sunset'] = sunset;
if (temp != null) {
data['temp'] = temp!.toJson();
}
if (feelsLike != null) {
data['feels_like'] = feelsLike!.toJson();
}
data['pressure'] = pressure;
data['humidity'] = humidity;
if (weather != null) {
data['weather'] = weather!.map((v) => v.toJson()).toList();
}
data['speed'] = speed;
data['deg'] = deg;
data['gust'] = gust;
data['clouds'] = clouds;
data['pop'] = pop;
data['rain'] = rain;
return data;
}
}
class Temp {
double? day;
double? min;
double? max;
double? night;
double? eve;
double? morn;
Temp(
{required this.day,
required this.min,
required this.max,
required this.night,
required this.eve,
required this.morn});
Temp.fromJson(Map<String, dynamic> json) {
day = json['day'];
min = json['min'];
max = json['max'];
night = json['night'];
eve = json['eve'];
morn = json['morn'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['day'] = day;
data['min'] = min;
data['max'] = max;
data['night'] = night;
data['eve'] = eve;
data['morn'] = morn;
return data;
}
}
class FeelsLike {
double? day;
double? night;
double? eve;
double? morn;
FeelsLike(
{required this.day,
required this.night,
required this.eve,
required this.morn});
FeelsLike.fromJson(Map<String, dynamic> json) {
day = json['day'];
night = json['night'];
eve = json['eve'];
morn = json['morn'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['day'] = day;
data['night'] = night;
data['eve'] = eve;
data['morn'] = morn;
return data;
}
}
class WeatherDetails {
int? id;
String? main;
String? description;
String? icon;
WeatherDetails(
{required this.id,
required this.main,
required this.description,
required this.icon});
WeatherDetails.fromJson(Map<String, dynamic> json) {
id = json['id'];
main = json['main'];
description = json['description'];
icon = json['icon'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['id'] = id;
data['main'] = main;
data['description'] = description;
data['icon'] = icon;
return data;
}
}
Below is the code for the network class:
class DataService {
Future<WeatherAppDetails> getWeather(String name) async {
final queryParameters = {
'q': name,
'appid': '3c044b7295d2df14f8bee74c19d4b96f',
'units': 'imperial',
'cnt': '7'
};
final uri = Uri.https(
'api.openweathermap.org', '/data/2.5/forecast/daily', queryParameters);
final response = await http.get(uri);
print(response.body);
if (response.statusCode == 200) {
return WeatherAppDetails.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to get posts');
}
}
}
Basically api.weather is telling you that the given value of "q" param does not exists, no geolocation found.
It´s helpful to add city param input
Your city input on the request is wrong, this should work (example)
https://api.openweathermap.org/data/2.5/forecast/daily?appid=3c044b7295d2df14f8bee74c19d4b96f&q=london,uk

Flutter Parsed Complex Json

I am having a problem on decoding the json from toMap(). I have no Issue on fromJson() function.
My main goal is to save it on shared preferences. all are working except for images i got null values
Here's my toMap() Method:
All Variables are working except for images;
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
ImagesModel img = ImagesModel();
Map<String, dynamic> imagesList = img.toMap();
map["id"] = id;
map["name"] = name;
map["description"] = description;
map["catalog_visibility"] = catalog_visibility;
map["short_description"] = short_description;
map["regular_price"] = regular_price;
map["sale_price"] = sale_price;
map["date_created"] = date_created;
map['images'] = imagesList; --> I got null value on this images
return map;
}
Here's my Image Model
class ImagesModel{
final int id;
final String src;
final String name;
ImagesModel({this.id, this.src, this.name});
factory ImagesModel.fromJSON(Map<String, dynamic> parsedJson){
return ImagesModel(
id: parsedJson['id'],
src: parsedJson['src'],
name: parsedJson['name']
);
}
Map<String, dynamic> toMap() => {
"id": id,
"src": src,
"name" :name,
};
}
My Whole Products Model
class ProductsModel {
final int id;
final String name;
final String catalog_visibility;
final String description;
final String short_description;
final String price;
final String regular_price;
final String sale_price;
final String date_created;
final List<CategoriesModel> categories;
final List<ImagesModel> images;
ProductsModel(
{this.id,
this.name,
this.catalog_visibility,
this.description,
this.short_description,
this.price,
this.regular_price,
this.sale_price,
this.date_created,
this.categories,
this.images
});
factory ProductsModel.fromJSON(Map<String, dynamic> parsedJson) {
var categoriesList = parsedJson['categories'] as List;
var imagesList = parsedJson['images'] as List;
List<ImagesModel> dataImages = imagesList.map((i) => ImagesModel.fromJSON(i)).toList();
List<CategoriesModel> dataCategories =
categoriesList.map((i) => CategoriesModel.fromJSON(i)).toList();
return ProductsModel(
id: parsedJson['id'],
name: parsedJson['name'],
catalog_visibility: parsedJson['catalog_visibility'],
description: parsedJson['description'],
short_description: parsedJson['short_description'],
regular_price: parsedJson['regular_price'],
sale_price: parsedJson['sale_price'],
date_created: parsedJson['date_created'],
categories: dataCategories,
images: dataImages
);
}
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
ImagesModel img = ImagesModel();
Map<String, dynamic> imagesList = img.toMap();
map["id"] = id;
map["name"] = name;
map["description"] = description;
map["catalog_visibility"] = catalog_visibility;
map["short_description"] = short_description;
map["regular_price"] = regular_price;
map["sale_price"] = sale_price;
map["date_created"] = date_created;
map['images'] = imagesList;
return map;
}
}
Just check imagesList null or not. Like
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
ImagesModel img = ImagesModel();
Map<String, dynamic> imagesList = img.toMap();
map["id"] = id;
map["name"] = name;
map["description"] = description;
map["catalog_visibility"] = catalog_visibility;
map["short_description"] = short_description;
map["regular_price"] = regular_price;
map["sale_price"] = sale_price;
map["date_created"] = date_created;
if (this.images != null) {
data['images'] = this.images.map((v) => v.toJson()).toList();
}
return map;
}
The constuctor function has no parameters. Check this out.
ImagesModel img = ImagesModel(id:1,src:'value',name:'value');
.
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
ImagesModel img = ImagesModel(id:1,src:'value',name:'value');
Map<String, dynamic> imagesList = img.toMap();
map["id"] = id;
map["name"] = name;
map["description"] = description;
map["catalog_visibility"] = catalog_visibility;
map["short_description"] = short_description;
map["regular_price"] = regular_price;
map["sale_price"] = sale_price;
map["date_created"] = date_created;
map['images'] = imagesList; --> I got null value on this images
return map;
}