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;
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();
}
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());
}
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
I'm getting NoSuchMethodError:The getter 'length' was called on null. Recevier:null. Tried calling:length error on this structure.
Basically I'm trying to find out the products list from json file and print the product's length.
It's give a response properly but when I try to convert json to dart by fromjson method then I'm facing above problem. I made my model class by online dart to json converter. So can you help me find out my problem?
Here is my repository part.
Future<List<Products>> getProducts() async {
final response = await http.post(AppStrings.productsListUrl,
body: {"store_uid": "demotest", "APIKey": "test03"});
if (response.statusCode == 200) {
print("success!!!!!");
var data = json.decode(response.body);
List<Products> products = Data.fromJson(data).products;
print(products.length);
return products;
} else {
print("Error");
throw Exception();
}}
And here is my model class
class ApiResultModel {
String status;
int code;
Data data;
List<String> message;
ApiResultModel({this.status, this.code, this.data, this.message});
ApiResultModel.fromJson(Map<String, dynamic> json) {
status = json['status'];
code = json['code'];
data = json['data'] != null ? new Data.fromJson(json['data']) : null;
message = json['message'].cast<String>();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['code'] = this.code;
if (this.data != null) {
data['data'] = this.data.toJson();
}
data['message'] = this.message;
return data;
}
}
class Data {
Paginator paginator;
int paginationLastPage;
List<Products> products;
Data({this.paginator, this.paginationLastPage, this.products});
Data.fromJson(Map<String, dynamic> json) {
paginator = json['paginator'] != null
? new Paginator.fromJson(json['paginator'])
: null;
paginationLastPage = json['pagination_last_page'];
if (json['products'] != null) {
products = new List<Products>();
json['products'].forEach((v) {
products.add(new Products.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.paginator != null) {
data['paginator'] = this.paginator.toJson();
}
data['pagination_last_page'] = this.paginationLastPage;
if (this.products != null) {
data['products'] = this.products.map((v) => v.toJson()).toList();
}
return data;
}
}
class Paginator {
int currentPage;
int totalPages;
Null previousPageUrl;
String nextPageUrl;
int recordPerPage;
Paginator(
{this.currentPage,
this.totalPages,
this.previousPageUrl,
this.nextPageUrl,
this.recordPerPage});
Paginator.fromJson(Map<String, dynamic> json) {
currentPage = json['current_page'];
totalPages = json['total_pages'];
previousPageUrl = json['previous_page_url'];
nextPageUrl = json['next_page_url'];
recordPerPage = json['record_per_page'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['current_page'] = this.currentPage;
data['total_pages'] = this.totalPages;
data['previous_page_url'] = this.previousPageUrl;
data['next_page_url'] = this.nextPageUrl;
data['record_per_page'] = this.recordPerPage;
return data;
}
}
class Products {
String productName;
String productSku;
String productSkuCode;
String checkoutRefCode;
String productDescription;
int price;
int priceInclTax;
String productThumbImage;
int productTypeId;
int isActive;
int isStockable;
int priceExclTax;
String storeName;
BrandInfo brandInfo;
Products(
{this.productName,
this.productSku,
this.productSkuCode,
this.checkoutRefCode,
this.productDescription,
this.price,
this.priceInclTax,
this.productThumbImage,
this.productTypeId,
this.isActive,
this.isStockable,
this.priceExclTax,
this.storeName,
this.brandInfo});
Products.fromJson(Map<String, dynamic> json) {
productName = json['product_name'];
productSku = json['product_sku'];
productSkuCode = json['product_sku_code'];
checkoutRefCode = json['checkout_ref_code'];
productDescription = json['product_description'];
price = json['price'];
priceInclTax = json['price_incl_tax'];
productThumbImage = json['product_thumb_image'];
productTypeId = json['product_type_id'];
isActive = json['is_active'];
isStockable = json['is_stockable'];
priceExclTax = json['price_excl_tax'];
storeName = json['store_name'];
brandInfo = json['brand_info'] != null
? new BrandInfo.fromJson(json['brand_info'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['product_name'] = this.productName;
data['product_sku'] = this.productSku;
data['product_sku_code'] = this.productSkuCode;
data['checkout_ref_code'] = this.checkoutRefCode;
data['product_description'] = this.productDescription;
data['price'] = this.price;
data['price_incl_tax'] = this.priceInclTax;
data['product_thumb_image'] = this.productThumbImage;
data['product_type_id'] = this.productTypeId;
data['is_active'] = this.isActive;
data['is_stockable'] = this.isStockable;
data['price_excl_tax'] = this.priceExclTax;
data['store_name'] = this.storeName;
if (this.brandInfo != null) {
data['brand_info'] = this.brandInfo.toJson();
}
return data;
}
}
class BrandInfo {
int id;
String brandName;
String brandCode;
int isActive;
String brandLogo;
String brandUid;
String storeUid;
BrandInfo(
{this.id,
this.brandName,
this.brandCode,
this.isActive,
this.brandLogo,
this.brandUid,
this.storeUid});
BrandInfo.fromJson(Map<String, dynamic> json) {
id = json['id'];
brandName = json['brand_name'];
brandCode = json['brand_code'];
isActive = json['is_active'];
brandLogo = json['brand_logo'];
brandUid = json['brand_uid'];
storeUid = json['store_uid'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['brand_name'] = this.brandName;
data['brand_code'] = this.brandCode;
data['is_active'] = this.isActive;
data['brand_logo'] = this.brandLogo;
data['brand_uid'] = this.brandUid;
data['store_uid'] = this.storeUid;
return data;
}
}
Your Data.fromJson is returning a null products list. I usually find it better to return an empty list in these scenarios, so you can add ?? List.empty() to the end of the line if you'd like. This helps to eliminate null pointer exceptions, or in this case, NoSuchMethod exceptions.
It's returning a null products list because the json['products']( in the if statement in your Data.fromJson constructor ) is null, so the list never gets initialized to an empty list;