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());
}
Related
the app.quicktype.io cannot convert.
they are converting and skip the digit class name
class ScoreCardModel {
bool? status;
String? msg;
Data? data;
ScoreCardModel({this.status, this.msg, this.data});
ScoreCardModel.fromJson(Map<String, dynamic> json) {
status = json['status'];
msg = json['msg'];
data = json['data'] = Data.fromJson(json['data']);
}
}
class Data {
String? result;
Scorecard? scorecard;
Data({this.result, this.scorecard});
Data.fromJson(Map<String, dynamic> json) {
result = json['result'];
scorecard = json['scorecard'] != null
? Scorecard.fromJson(json['scorecard'])
: null;
}
}
the quicktype cannot work with digits, I don't know why is this. I think they are in the developing stage. I Have the answer. I'm looking for the correct answer.
You can use https://jsontodart.com/, They are just including digit as model(Class) name. But You have to rename the model name like follows,
class 1 {
String score;
String wicket;
String ball;
1({this.score, this.wicket, this.ball});
1.fromJson(Map<String, dynamic> json) {
score = json['score'];
wicket = json['wicket'];
ball = json['ball'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['score'] = this.score;
data['wicket'] = this.wicket;
data['ball'] = this.ball;
return data;
}
}
to
class teamA {
String score;
String wicket;
String ball;
teamA({this.score, this.wicket, this.ball});
teamA.fromJson(Map<String, dynamic> json) {
score = json['score'];
wicket = json['wicket'];
ball = json['ball'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['score'] = this.score;
data['wicket'] = this.wicket;
data['ball'] = this.ball;
return data;
}
}
I am calling an api and it returns a json data and this data i embedding with the model by using online converter. Below is the sample json data and model
JSON
{
"message": "menues returned by Dish Type successfully",
"data": [
{
"id": "10"
}
]
}
Model
class DishMenuTypesIdData {
String? id;
DishMenuTypesIdData({
this.id,
});
DishMenuTypesIdData.fromJson(Map<String, dynamic> json) {
id = json["id"]?.toString();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data["id"] = id;
return data;
}
}
class DishMenuTypesId {
String? message;
List<DishMenuTypesIdData?>? data;
DishMenuTypesId({
this.message,
this.data,
});
DishMenuTypesId.fromJson(Map<String, dynamic> json) {
message = json["message"]?.toString();
if (json["data"] != null) {
final v = json["data"];
final arr0 = <DishMenuTypesIdData>[];
v.forEach((v) {
arr0.add(DishMenuTypesIdData.fromJson(v));
});
this.data = arr0;
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data["message"] = message;
if (this.data != null) {
final v = this.data;
final arr0 = [];
v!.forEach((v) {
arr0.add(v!.toJson());
});
data["data"] = arr0;
}
return data;
}
}
Now i decided to add a variable qty and initialize qty in existing model which will be
int qty;
And in constructor it will be
this.qty = 1;
But when i call this qty in ui then it is getting null. Although i initialize this qty in constructor equals 1
Model After including qty
class DishMenuTypesIdData {
String? qty;
String? id;
DishMenuTypesIdData({
this.qty = "1",
this.id,
});
DishMenuTypesIdData.fromJson(Map<String, dynamic> json) {
qty = json["qty"]?.toString();
id = json["id"]?.toString();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data["qty"] = qty;
data["id"] = id;
return data;
}
}
class DishMenuTypesId {
String? message;
List<DishMenuTypesIdData?>? data;
DishMenuTypesId({
this.message,
this.data,
});
DishMenuTypesId.fromJson(Map<String, dynamic> json) {
message = json["message"]?.toString();
if (json["data"] != null) {
final v = json["data"];
final arr0 = <DishMenuTypesIdData>[];
v.forEach((v) {
arr0.add(DishMenuTypesIdData.fromJson(v));
});
this.data = arr0;
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data["message"] = message;
if (this.data != null) {
final v = this.data;
final arr0 = [];
v!.forEach((v) {
arr0.add(v!.toJson());
});
data["data"] = arr0;
}
return data;
}
}
The server is not returning the qty when being called, thus the qty will be null.
qty = json["qty"]?.toString();
if you want to initialize it to 1, you need to replace this line with:
qty = "1";
I have created one model like this :
class SalesRepResponse {
bool errors;
List<Data> data;
int statusCode;
SalesRepResponse({this.errors, this.data, this.statusCode});
SalesRepResponse.fromJson(Map<String, dynamic> json) {
errors = json['errors'];
if (json['data'] != null) {
data = new List<Data>();
json['data'].forEach((v) {
data.add(new Data.fromJson(v));
});
}
statusCode = json['status_code'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['errors'] = this.errors;
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
data['status_code'] = this.statusCode;
return data;
}
}
class Data {
int id;
String displayName;
Data({this.id, this.displayName});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
displayName = json['display_name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['display_name'] = this.displayName;
return data;
}
}
And i get the same response from API also and i parse data like this :
var result = SalesRepResponse.fromJson(json.decode(response1.body));
But it stores all the value in SalesRepResponse/Data class as null.
Someone please help me with this.
Thanks in advance.
you have to specify the data in your json like this
var result = SalesRepResponse.fromJson(json.decode(response1.body['data/etc']));
mean that u have to specify the data which have data for SalesRepResponse by checking your json response
I am able to fetch the json data in flutter applicaion.
Now I want to associate that data with the List.
How should I do that?
List companydetails;
var jsonResponse = json.decode(response.body);
JSON DATA
{"error":"false","content":[
{
"id":"22","name":"Johnny",},
{"id":"23","name":"Maria",},
]
}
I need to build a list view in flutter from the fetched data.
You can use this model:
class CompanyDetail {
String error;
List<Content> content;
CompanyDetail({this.error, this.content});
CompanyDetail.fromJson(Map<String, dynamic> json) {
error = json['error'];
if (json['content'] != null) {
content = new List<Content>();
json['content'].forEach((v) {
content.add(new Content.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['error'] = this.error;
if (this.content != null) {
data['content'] = this.content.map((v) => v.toJson()).toList();
}
return data;
}
}
class Content {
String id;
String name;
Content({this.id, this.name});
Content.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
Then bind the Json data:
var companyDetail = CompanyDetail.fromJson(json.decode(response.body));
Now use Content List in your ListView widget:
companyDetail.content
Example (make sure that content is not null):
....
ListView.builder
(
itemCount: companyDetail.content.length,
itemBuilder: (BuildContext ctxt, int index) {
return new Text(companyDetail.content[index]);
}
),
...
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;