Flutter image associated with color - json

I'm making an API to show the product image and colors,
whenever the user press on a color button, the image which is associated with that color should show using PageView.builder.
how can I make model factory for the api if this is my json?
[
{
"id": 7,
"name": "1",
"descriptions": "1",
"price": 1,
"discount": 1,
"category": "new",
"quantity": 1,
"brand": "1",
"image": "",
"created_at": "2019-08-04 09:07:25",
"updated_at": "2019-08-04 09:07:25",
"images": {
"url":"1564909645iKiw2LkoEcQIIhB4MTZJTUfwTREleWH4wEuvmRPd.png",
"color":"#fffddd"
},
"tags": [
"large"
],
"sizes": []
}
]
my model and factory:
class Response1 {
final String createdAt;
final int id;
final int quantity;
final double price;
final String name;
final String descriptions;
final String updatedAt;
final String image;
final int weight;
final List images;
final List tags;
final List sizes;
Response1(
{this.createdAt,
this.id,
this.quantity,
this.price,
this.name,
this.descriptions,
this.updatedAt,
this.image,
this.weight,
this.images,
this.tags,
this.sizes});
factory Response1.fromJson(Map<String, dynamic> json) {
return Response1(
createdAt: json['created_at'] as String,
id: json['id'] as int,
quantity: json['quantity'] as int,
price: _toDouble(json['price']),
name: json['name'] as String,
updatedAt: json['updated_at'] as String,
image: json['image'] as String,
descriptions: json['descriptions'] as String,
weight: json['weight'] as int,
images: json['images'] as List,
tags: json['tags'] as List,
sizes: json['sizes'] as List,
);
}
Map<String, dynamic> toJson() {
return {
'created_at': createdAt,
'id': id,
'quantity': quantity,
'price': price,
'name': name,
'updated_at': updatedAt,
'image': image,
'weight': weight,
'images': images,
'tags': tags,
'sizes': sizes,
};
}
}
how can I do it? is there another way?
thanks

you can use https://app.quicktype.io/ to help you simplify this aciton
the code you need please see below
// To parse this JSON data, do
//
// final response1 = response1FromJson(jsonString);
import 'dart:convert';
List<Response1> response1FromJson(String str) => new List<Response1>.from(json.decode(str).map((x) => Response1.fromJson(x)));
String response1ToJson(List<Response1> data) => json.encode(new List<dynamic>.from(data.map((x) => x.toJson())));
class Response1 {
int id;
String name;
String descriptions;
int price;
int discount;
String category;
int quantity;
String brand;
String image;
DateTime createdAt;
DateTime updatedAt;
Images images;
List<String> tags;
List<dynamic> sizes;
Response1({
this.id,
this.name,
this.descriptions,
this.price,
this.discount,
this.category,
this.quantity,
this.brand,
this.image,
this.createdAt,
this.updatedAt,
this.images,
this.tags,
this.sizes,
});
factory Response1.fromJson(Map<String, dynamic> json) => new Response1(
id: json["id"],
name: json["name"],
descriptions: json["descriptions"],
price: json["price"],
discount: json["discount"],
category: json["category"],
quantity: json["quantity"],
brand: json["brand"],
image: json["image"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
images: Images.fromJson(json["images"]),
tags: new List<String>.from(json["tags"].map((x) => x)),
sizes: new List<dynamic>.from(json["sizes"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"descriptions": descriptions,
"price": price,
"discount": discount,
"category": category,
"quantity": quantity,
"brand": brand,
"image": image,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
"images": images.toJson(),
"tags": new List<dynamic>.from(tags.map((x) => x)),
"sizes": new List<dynamic>.from(sizes.map((x) => x)),
};
}
class Images {
String url;
String color;
Images({
this.url,
this.color,
});
factory Images.fromJson(Map<String, dynamic> json) => new Images(
url: json["url"],
color: json["color"],
);
Map<String, dynamic> toJson() => {
"url": url,
"color": color,
};
}

Related

flutter multiple json data/nested

i have my api which returns the json data, within the json there is multiple nested parts that i want to use. i have my models setup. how do i return them back to my futurebuilder and then use them i.e.
snapshot.data['media'][0].fieldname or snapshot.data['locationData'][0].fieldname.
I have change the code back so at the moment it only returns the LocationData but not the MediaData. this is the part i need help with returning all of it at the same time to use on my page.
here is what the json looks like when i get it back from the api
{
"recordsTotal": 1,
"sensordate": "2022-01-20",
"data": [
{
"id": 2,
"locationname": "The Old Man of Storr",
"description": "",
"shortdescription":"",
"latitude": "55.9486",
"longitude": " -3.1910",
"mainimageurl": "",
"road": "",
"addressline1": "",
"addressline2": "",
"town": "",
"county": "",
"postcode": "",
"areaid": 2,
"headerimageid": 450,
"carparkcapacity": 100,
"title": "Old Town",
"originalfilename": "OldTown.jpg",
"ext": "jpg",
"alttext": "Old Town",
"savelocation": "/library/images/locations/",
"filename": "cd8d5c511f3b64758238e75c1aa7c84d"
}
],
"media": [
{
"locationid": 2,
"mediaid": 32,
"title": "Old Town History",
"systemfilename": "/library/media/64c8ba08a781ef8b8b2a08c62d0427b6.mp3",
"transcriptionnotes": "Transcription of media file",
"mediatype": "audio",
"originalfilename": "oldtown.mp3",
"locationname": "Old Town"
}
]
}
//This is my 2 models
class LocationData {
final int id;
final String locationname;
final String description;
final String shortdescription;
final double latitude;
final double longitude;
final String mainimageurl;
final String imagefilename;
final String imagelocation;
final String imageext;
final int carparkcapacity;
final int areaid;
LocationData(
{required this.id,
required this.locationname,
required this.description,
required this.carparkcapacity,
required this.areaid,
required this.imageext,
required this.imagefilename,
required this.imagelocation,
required this.latitude,
required this.longitude,
required this.mainimageurl,
required this.shortdescription,
});
factory LocationData.fromJson(json) => LocationData(
locationname: json['locationname'],
id: json['id'] == null ? 0 : json["id"],
latitude: double.parse(json['latitude']),
longitude: double.parse(json['longitude']),
areaid: json['areaid'] == null ? 0 : json["areaid"],
description: json['description'] == null
? 'Welcome to Skye'
: json["description"],
shortdescription: json['shortdescription'] == null
? 'Welcome'
: json["shortdescription"],
imageext: json['ext'] == null ? 'jpg' : json["ext"],
carparkcapacity:
json['carparkcapacity'] == null ? 0 : json["carparkcapacity"],
imagefilename:
json['filename'] == null ? 'logo' : json["filename"],
imagelocation: json['savelocation'] == null
? '/assets/imgs/'
: json["savelocation"],
mainimageurl: json['mainimageurl'] == null
? '/assets/imgs/logo.jpg'
: json["mainimageurl"],
);
}
//Similar to above
class MediaData{}
//Getting the data
class LocationDataApi {
static Future<List<LocationData>> getLocationData(
String locationName) async {
final hotspotLocationsURL =
'${config.apiUrl}/locations.php?action=get_location&location=' +
locationName;
try {
final response = await http.get(Uri.parse(hotspotLocationsURL));
if (response.statusCode == 200) {
final body = json.decode(response.body);
//Returned Data
return body['data'].map<LocationData>(LocationData.fromJson).toList();
} else {
throw 'Error Retrieving Data';
}
} catch (e) {
if (kDebugMode) {
print(e);
}
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load Location Data');
}
}
}
on my page
class _AlreadyHereState extends State<AlreadyHere> {
late Future<List<LocationData>> _locationData;
}
....other code
FutureBuilder(
future: _locationData,
builder: (BuildContext context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.error != null) {
return const Center(child: Text('an error occured!'));
} else {
//this part how do i get the data? snapshot.data['media'][0].fieldname doesnt work/
for starters, you can change your model to look this
// To parse this JSON data, do
//
// final someClass = someClassFromJson(jsonString);
import 'package:meta/meta.dart';
import 'dart:convert';
class SomeClass {
SomeClass({
required this.recordsTotal,
required this.sensordate,
required this.data,
required this.media,
});
final int recordsTotal;
final DateTime sensordate;
final List<Datum> data;
final List<Media> media;
factory SomeClass.fromRawJson(String str) => SomeClass.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory SomeClass.fromJson(Map<String, dynamic> json) => SomeClass(
recordsTotal: json["recordsTotal"],
sensordate: DateTime.parse(json["sensordate"]),
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
media: List<Media>.from(json["media"].map((x) => Media.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"recordsTotal": recordsTotal,
"sensordate": "${sensordate.year.toString().padLeft(4, '0')}-${sensordate.month.toString().padLeft(2, '0')}-${sensordate.day.toString().padLeft(2, '0')}",
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"media": List<dynamic>.from(media.map((x) => x.toJson())),
};
}
class Datum {
Datum({
required this.id,
required this.locationname,
required this.description,
required this.shortdescription,
required this.latitude,
required this.longitude,
required this.mainimageurl,
required this.road,
required this.addressline1,
required this.addressline2,
required this.town,
required this.county,
required this.postcode,
required this.areaid,
required this.headerimageid,
required this.carparkcapacity,
required this.title,
required this.originalfilename,
required this.ext,
required this.alttext,
required this.savelocation,
required this.filename,
});
final int id;
final String locationname;
final String description;
final String shortdescription;
final String latitude;
final String longitude;
final String mainimageurl;
final String road;
final String addressline1;
final String addressline2;
final String town;
final String county;
final String postcode;
final int areaid;
final int headerimageid;
final int carparkcapacity;
final String title;
final String originalfilename;
final String ext;
final String alttext;
final String savelocation;
final String filename;
factory Datum.fromRawJson(String str) => Datum.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
locationname: json["locationname"],
description: json["description"],
shortdescription: json["shortdescription"],
latitude: json["latitude"],
longitude: json["longitude"],
mainimageurl: json["mainimageurl"],
road: json["road"],
addressline1: json["addressline1"],
addressline2: json["addressline2"],
town: json["town"],
county: json["county"],
postcode: json["postcode"],
areaid: json["areaid"],
headerimageid: json["headerimageid"],
carparkcapacity: json["carparkcapacity"],
title: json["title"],
originalfilename: json["originalfilename"],
ext: json["ext"],
alttext: json["alttext"],
savelocation: json["savelocation"],
filename: json["filename"],
);
Map<String, dynamic> toJson() => {
"id": id,
"locationname": locationname,
"description": description,
"shortdescription": shortdescription,
"latitude": latitude,
"longitude": longitude,
"mainimageurl": mainimageurl,
"road": road,
"addressline1": addressline1,
"addressline2": addressline2,
"town": town,
"county": county,
"postcode": postcode,
"areaid": areaid,
"headerimageid": headerimageid,
"carparkcapacity": carparkcapacity,
"title": title,
"originalfilename": originalfilename,
"ext": ext,
"alttext": alttext,
"savelocation": savelocation,
"filename": filename,
};
}
class Media {
Media({
required this.locationid,
required this.mediaid,
required this.title,
required this.systemfilename,
required this.transcriptionnotes,
required this.mediatype,
required this.originalfilename,
required this.locationname,
});
final int locationid;
final int mediaid;
final String title;
final String systemfilename;
final String transcriptionnotes;
final String mediatype;
final String originalfilename;
final String locationname;
factory Media.fromRawJson(String str) => Media.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Media.fromJson(Map<String, dynamic> json) => Media(
locationid: json["locationid"],
mediaid: json["mediaid"],
title: json["title"],
systemfilename: json["systemfilename"],
transcriptionnotes: json["transcriptionnotes"],
mediatype: json["mediatype"],
originalfilename: json["originalfilename"],
locationname: json["locationname"],
);
Map<String, dynamic> toJson() => {
"locationid": locationid,
"mediaid": mediaid,
"title": title,
"systemfilename": systemfilename,
"transcriptionnotes": transcriptionnotes,
"mediatype": mediatype,
"originalfilename": originalfilename,
"locationname": locationname,
};
}
and then inside FutureBuilder use like this
FutureBuilder(
future: _locationData,
// Add <T> to the Asyncsnapshot class
builder: (BuildContext context, AsyncSnapshot<SomeClass> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.error != null) {
return const Center(child: Text('an error occured!'));
} else {
print(snapshot.data.data[0].longitude);
print(snapshot.data.media[0].title);
}

Flutter Rest Api Connection - How to get data?

I am a beginner in Flutter. I was trying to extract data from api. I got response like this
"status": "success",
"data": {
"integration": "051st93cqk90gqeyuikkkii1s5il5d3p",
"rootcategory": 2,
"slider": [
{
"image": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60b787d5beb55.png",
"type": "category",
"id": "6",
"sort_order": "0.00"
},
{
"image": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60b787fb306c7.png",
"type": "product",
"id": "5",
"sort_order": "1.00"
}
],
"noimg": "https://omanphone.smsoman.com/api/media/omanphone_icon.png",
"catimages": [
{
"id": "6",
"img": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60b4857e526dd.jpg"
},
{
"id": "7",
"img": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60ba1d4142c0b.jpeg"
},
{
"id": "8",
"img": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60ba1d6440439.jpeg"
},
{
"id": "11",
"img": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60ba1d7c6974c.jpeg"
}
],
"store_id": 1,
"minimum_order_amount": null,
"stores": [
],
"currency": "OMR",
"payment_imgs": [
"https://omanphone.smsoman.com/api/media/payment_all.png",
"https://omanphone.smsoman.com/api/media/cards.png"
],
"voucher_cat": 151,
"whatsapp": "96812345678",
"celebrity_id": 0,
"register_otp": "0",
"mobile_formats": [
{
"webiste": "base",
"len": 8,
"country_code": "+968",
"country": "OM",
"id": 1
}
],
"cmspages": {
"faq": 73,
"about": 72,
"terms": 71,
"privacy": 70
},
"pay_method_imgs": [
"https://omanphone.smsoman.com/pub/media/itoons/payment-icon.png",
"https://omanphone.smsoman.com/pub/media/itoons/cod-icon.png"
]
}
}
Using app.quicktype.io - I converted this data to model.
like below.
// To parse this JSON data, do
//
// final slideData = slideDataFromJson(jsonString);
import 'dart:convert';
SlideData slideDataFromJson(String str) => SlideData.fromJson(json.decode(str));
String slideDataToJson(SlideData data) => json.encode(data.toJson());
class SlideData {
SlideData({
this.status,
this.data,
});
String status;
Data data;
factory SlideData.fromJson(Map<String, dynamic> json) => SlideData(
status: json["status"],
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"status": status,
"data": data.toJson(),
};
}
class Data {
Data({
this.integration,
this.rootcategory,
this.slider,
this.noimg,
this.catimages,
this.storeId,
this.minimumOrderAmount,
this.stores,
this.currency,
this.paymentImgs,
this.voucherCat,
this.whatsapp,
this.celebrityId,
this.registerOtp,
this.mobileFormats,
this.cmspages,
this.payMethodImgs,
});
String integration;
int rootcategory;
List<Slider> slider;
String noimg;
List<Catimage> catimages;
int storeId;
dynamic minimumOrderAmount;
List<dynamic> stores;
String currency;
List<String> paymentImgs;
int voucherCat;
String whatsapp;
int celebrityId;
String registerOtp;
List<MobileFormat> mobileFormats;
Cmspages cmspages;
List<String> payMethodImgs;
factory Data.fromJson(Map<String, dynamic> json) => Data(
integration: json["integration"],
rootcategory: json["rootcategory"],
slider: List<Slider>.from(json["slider"].map((x) => Slider.fromJson(x))),
noimg: json["noimg"],
catimages: List<Catimage>.from(json["catimages"].map((x) => Catimage.fromJson(x))),
storeId: json["store_id"],
minimumOrderAmount: json["minimum_order_amount"],
stores: List<dynamic>.from(json["stores"].map((x) => x)),
currency: json["currency"],
paymentImgs: List<String>.from(json["payment_imgs"].map((x) => x)),
voucherCat: json["voucher_cat"],
whatsapp: json["whatsapp"],
celebrityId: json["celebrity_id"],
registerOtp: json["register_otp"],
mobileFormats: List<MobileFormat>.from(json["mobile_formats"].map((x) => MobileFormat.fromJson(x))),
cmspages: Cmspages.fromJson(json["cmspages"]),
payMethodImgs: List<String>.from(json["pay_method_imgs"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"integration": integration,
"rootcategory": rootcategory,
"slider": List<dynamic>.from(slider.map((x) => x.toJson())),
"noimg": noimg,
"catimages": List<dynamic>.from(catimages.map((x) => x.toJson())),
"store_id": storeId,
"minimum_order_amount": minimumOrderAmount,
"stores": List<dynamic>.from(stores.map((x) => x)),
"currency": currency,
"payment_imgs": List<dynamic>.from(paymentImgs.map((x) => x)),
"voucher_cat": voucherCat,
"whatsapp": whatsapp,
"celebrity_id": celebrityId,
"register_otp": registerOtp,
"mobile_formats": List<dynamic>.from(mobileFormats.map((x) => x.toJson())),
"cmspages": cmspages.toJson(),
"pay_method_imgs": List<dynamic>.from(payMethodImgs.map((x) => x)),
};
}
class Catimage {
Catimage({
this.id,
this.img,
});
String id;
String img;
factory Catimage.fromJson(Map<String, dynamic> json) => Catimage(
id: json["id"],
img: json["img"],
);
Map<String, dynamic> toJson() => {
"id": id,
"img": img,
};
}
class Cmspages {
Cmspages({
this.faq,
this.about,
this.terms,
this.privacy,
});
int faq;
int about;
int terms;
int privacy;
factory Cmspages.fromJson(Map<String, dynamic> json) => Cmspages(
faq: json["faq"],
about: json["about"],
terms: json["terms"],
privacy: json["privacy"],
);
Map<String, dynamic> toJson() => {
"faq": faq,
"about": about,
"terms": terms,
"privacy": privacy,
};
}
class MobileFormat {
MobileFormat({
this.webiste,
this.len,
this.countryCode,
this.country,
this.id,
});
String webiste;
int len;
String countryCode;
String country;
int id;
factory MobileFormat.fromJson(Map<String, dynamic> json) => MobileFormat(
webiste: json["webiste"],
len: json["len"],
countryCode: json["country_code"],
country: json["country"],
id: json["id"],
);
Map<String, dynamic> toJson() => {
"webiste": webiste,
"len": len,
"country_code": countryCode,
"country": country,
"id": id,
};
}
class Slider {
Slider({
this.image,
this.type,
this.id,
this.sortOrder,
});
String image;
String type;
String id;
String sortOrder;
factory Slider.fromJson(Map<String, dynamic> json) => Slider(
image: json["image"],
type: json["type"],
id: json["id"],
sortOrder: json["sort_order"],
);
Map<String, dynamic> toJson() => {
"image": image,
"type": type,
"id": id,
"sort_order": sortOrder,
};
}
Future<void> getDataFromInternet() async {
//getting data from Internet
try {
var response =
await http.get('https://omanphone.smsoman.com/api/configuration');
} catch (error) {
print(error);
}
}
I just want to get slider images. So What did I need to do in above code?
I used http package and var response =
await http.get('https://omanphone.smsoman.com/api/configuration'); did this. But I don't know how to extract it.

How to create a json in dart (Exception Instance of '_CompactLinkedHashSet)

I'm trying to convert some objects to json to send it to DB, this is the code I have now:
Map<String, dynamic> bag = {};
bag = {
'colors' : [
for(int i = 0; i < product.colors.length; i ++){
'id': product.colors[i].id,
'desc': product.colors[i].desc,
'sizes': [
for(int j=0; j < product.colors[i].sizes.length; j ++){
product.colors[i].sizes[j].toJson()
}
]
}]
};
print(json.encode(bag));
but the result I get is this:
Converting object to an encodable object failed: Instance of '_CompactLinkedHashSet<Map<String, dynamic>>'
How can I solve it?
Product class:
final String id;
final String desc;
final List<Colors> colors;
Colors:
final String id;
final String desc;
final List<Prices> prices;
Prices:
final String id;
final String desc;
final List<Types> types;
Types:
final String id;
final String desc;
final List<Sizes> sizes;
Sizes:
final String id;
final int stock;
final String desc;
final bool filled;
int quantity;
final double price;
I want the json like this:
colors:
id : 12
desc : black
sizes: [
id : 0202202
stock : 10
desc: Full Size
filled: true
quantity : 2
price : 200
]
The way you are creating the JSON is way too complicated. Try instead add a toJson() method on each of your classes. This method is automatically called by the Dart JSON encoder if it hits an object that is not compatible with JSON.
Here is an example:
import 'dart:convert';
class Product {
final String id;
final String desc;
final List<Colors> colors;
Product({
required this.id,
required this.desc,
required this.colors,
});
Map<String, Object> toJson() => {
'id': id,
'desc': desc,
'colors': colors,
};
}
class Colors {
final int id;
final String desc;
final List<Prices> prices;
Colors({
required this.id,
required this.desc,
required this.prices,
});
Map<String, Object> toJson() => {
'id': id,
'desc': desc,
'prices': prices,
};
}
class Prices {
final String id;
final String desc;
final List<Types> types;
Prices({
required this.id,
required this.desc,
required this.types,
});
Map<String, Object> toJson() => {
'id': id,
'desc': desc,
'types': types,
};
}
class Types {
final String id;
final String desc;
final List<Sizes> sizes;
Types({
required this.id,
required this.desc,
required this.sizes,
});
Map<String, Object> toJson() => {
'id': id,
'desc': desc,
'sizes': sizes,
};
}
class Sizes {
final String id;
final int stock;
final String desc;
final bool filled;
int quantity;
final double price;
Sizes({
required this.id,
required this.stock,
required this.desc,
required this.filled,
required this.quantity,
required this.price,
});
Map<String, Object> toJson() => {
'id': id,
'stock': stock,
'desc': desc,
'filled': filled,
'quantity': quantity,
'price': price,
};
}
void main() {
final product = Product(id: '1', desc: 'Some text', colors: [
Colors(id: 1, desc: '', prices: [
Prices(id: '1', desc: '', types: [
Types(id: '1', desc: '', sizes: [
Sizes(
id: '1',
stock: 5,
desc: '',
filled: true,
quantity: 2,
price: 1.0)
])
])
]),
Colors(id: 2, desc: '', prices: [
Prices(id: '1', desc: '', types: [
Types(id: '1', desc: '', sizes: [
Sizes(
id: '5',
stock: 5,
desc: '',
filled: true,
quantity: 2,
price: 1.0),
Sizes(
id: '50',
stock: 5,
desc: '',
filled: true,
quantity: 2,
price: 1.0),
])
])
])
]);
final bag = {
'colors': [
for (final colors in product.colors)
{
'id': colors.id,
'desc': colors.desc,
'sizes': [
for (final prices in colors.prices)
for (final types in prices.types) ...types.sizes
]
}
]
};
print(const JsonEncoder.withIndent(' ').convert(bag));
}
Output:
{
"colors": [
{
"id": 1,
"desc": "",
"sizes": [
{
"id": "1",
"stock": 5,
"desc": "",
"filled": true,
"quantity": 2,
"price": 1.0
}
]
},
{
"id": 2,
"desc": "",
"sizes": [
{
"id": "5",
"stock": 5,
"desc": "",
"filled": true,
"quantity": 2,
"price": 1.0
},
{
"id": "50",
"stock": 5,
"desc": "",
"filled": true,
"quantity": 2,
"price": 1.0
}
]
}
]
}
A trick here is that Dart will call object inside a structure returned from another toJson() call. So e.g. Product.toJson returns a Map<String, Object> which contains a list of colors. Dart are then calling the toJson() on each of these colors and so on.
This should help you, it's better to convert to json when you have maps, so you need to convert the class and it's subclasses to maps, and in the end it will be simple to convert to json.
Product class to map:
class Product {
final String id;
final String desc;
final List<Colors> colors;
Product(this.id, this.desc, this.colors);
Map toMap() {
return {
'id': this.id,
'desc': this.desc,
'colors': this.colors.map((color) => color.toMap()).toList(),
};
}
}
Colors class to map:
class Colors {
final String id;
final String desc;
final List<Sizes> sizes;
Colors(this.id, this.desc, this.sizes);
Map toMap() {
return {
'id': this.id,
'desc': this.desc,
'sizes': this.sizes.map((size) => size.toMap()).toList(),
};
}
}
Sizes class to map:
class Sizes {
final String id;
final int stock;
final String desc;
final bool filled;
int quantity;
final double price;
Sizes(this.id, this.stock, this.desc, this.filled, this.quantity, this.price);
Map toMap() {
return {
'id': this.id,
'stock': this.stock,
'desc': this.desc,
'filled': this.filled,
'quantity': this.quantity,
'price': this.price,
};
}
}
Result:
Product product = Product(...);
Map map = product.toMap();
String json = jsonEncode(map);

Dart issue with getting JSON data

I'm trying to get data from JSON, the data is as follows :
For the JSON above, I've generated a Dart Class using this website
the code below works fine with this response : RESPONSE TVSHOW DETAILS, I can see all data loaded successfully in my app, but not with this one RESPONSE TVSHOW DETAILS 2, nothing is loaded
TVShow tvShowFromJson(String str) => TVShow.fromJson(json.decode(str));
String tvShowToJson(TVShow data) => json.encode(data.toJson());
class TVShow {
String backdropPath;
List<CreatedBy> createdBy;
List<int> episodeRunTime;
DateTime firstAirDate;
List<Genre> genres;
String homepage;
int id;
bool inProduction;
List<String> languages;
DateTime lastAirDate;
TEpisodeToAir lastEpisodeToAir;
String name;
TEpisodeToAir nextEpisodeToAir;
List<Network> networks;
int numberOfEpisodes;
int numberOfSeasons;
List<String> originCountry;
String originalLanguage;
String originalName;
String overview;
double popularity;
String posterPath;
List<Network> productionCompanies;
List<Season> seasons;
String status;
String type;
double voteAverage;
int voteCount;
TVShow({
this.backdropPath,
this.createdBy,
this.episodeRunTime,
this.firstAirDate,
this.genres,
this.homepage,
this.id,
this.inProduction,
this.languages,
this.lastAirDate,
this.lastEpisodeToAir,
this.name,
this.nextEpisodeToAir,
this.networks,
this.numberOfEpisodes,
this.numberOfSeasons,
this.originCountry,
this.originalLanguage,
this.originalName,
this.overview,
this.popularity,
this.posterPath,
this.productionCompanies,
this.seasons,
this.status,
this.type,
this.voteAverage,
this.voteCount,
});
factory TVShow.fromJson(Map<String, dynamic> json) => TVShow(
backdropPath: json["backdrop_path"],
createdBy: List<CreatedBy>.from(json["created_by"].map((x) => CreatedBy.fromJson(x))),
episodeRunTime: List<int>.from(json["episode_run_time"].map((x) => x)),
firstAirDate: DateTime.parse(json["first_air_date"]),
genres: List<Genre>.from(json["genres"].map((x) => Genre.fromJson(x))),
homepage: json["homepage"],
id: json["id"],
inProduction: json["in_production"],
languages: List<String>.from(json["languages"].map((x) => x)),
lastAirDate: DateTime.parse(json["last_air_date"]),
lastEpisodeToAir: TEpisodeToAir.fromJson(json["last_episode_to_air"]),
name: json["name"],
nextEpisodeToAir: TEpisodeToAir.fromJson(json["next_episode_to_air"]),
networks: List<Network>.from(json["networks"].map((x) => Network.fromJson(x))),
numberOfEpisodes: json["number_of_episodes"],
numberOfSeasons: json["number_of_seasons"],
originCountry: List<String>.from(json["origin_country"].map((x) => x)),
originalLanguage: json["original_language"],
originalName: json["original_name"],
overview: json["overview"],
popularity: json["popularity"].toDouble(),
posterPath: json["poster_path"],
productionCompanies: List<Network>.from(json["production_companies"].map((x) => Network.fromJson(x))),
seasons: List<Season>.from(json["seasons"].map((x) => Season.fromJson(x))),
status: json["status"],
type: json["type"],
voteAverage: json["vote_average"].toDouble(),
voteCount: json["vote_count"],
);
Map<String, dynamic> toJson() => {
"backdrop_path": backdropPath,
"created_by": List<dynamic>.from(createdBy.map((x) => x.toJson())),
"episode_run_time": List<dynamic>.from(episodeRunTime.map((x) => x)),
"first_air_date":
"${firstAirDate.year.toString().padLeft(4, '0')}-${firstAirDate.month.toString().padLeft(2, '0')}-${firstAirDate.day.toString().padLeft(2, '0')}",
"genres": List<dynamic>.from(genres.map((x) => x.toJson())),
"homepage": homepage,
"id": id,
"in_production": inProduction,
"languages": List<dynamic>.from(languages.map((x) => x)),
"last_air_date":
"${lastAirDate.year.toString().padLeft(4, '0')}-${lastAirDate.month.toString().padLeft(2, '0')}-${lastAirDate.day.toString().padLeft(2, '0')}",
"last_episode_to_air": lastEpisodeToAir.toJson(),
"name": name,
"next_episode_to_air": nextEpisodeToAir.toJson(),
"networks": List<dynamic>.from(networks.map((x) => x.toJson())),
"number_of_episodes": numberOfEpisodes,
"number_of_seasons": numberOfSeasons,
"origin_country": List<dynamic>.from(originCountry.map((x) => x)),
"original_language": originalLanguage,
"original_name": originalName,
"overview": overview,
"popularity": popularity,
"poster_path": posterPath,
"production_companies": List<dynamic>.from(productionCompanies.map((x) => x.toJson())),
"seasons": List<dynamic>.from(seasons.map((x) => x.toJson())),
"status": status,
"type": type,
"vote_average": voteAverage,
"vote_count": voteCount,
};
}
class CreatedBy {
int id;
String creditId;
String name;
int gender;
String profilePath;
CreatedBy({
this.id,
this.creditId,
this.name,
this.gender,
this.profilePath,
});
factory CreatedBy.fromJson(Map<String, dynamic> json) => CreatedBy(
id: json["id"],
creditId: json["credit_id"],
name: json["name"],
gender: json["gender"],
profilePath: json["profile_path"],
);
Map<String, dynamic> toJson() => {
"id": id,
"credit_id": creditId,
"name": name,
"gender": gender,
"profile_path": profilePath,
};
}
class Genre {
int id;
String name;
Genre({
this.id,
this.name,
});
factory Genre.fromJson(Map<String, dynamic> json) => Genre(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
class TEpisodeToAir {
DateTime airDate;
int episodeNumber;
int id;
String name;
String overview;
String productionCode;
int seasonNumber;
int showId;
String stillPath;
double voteAverage;
int voteCount;
TEpisodeToAir({
this.airDate,
this.episodeNumber,
this.id,
this.name,
this.overview,
this.productionCode,
this.seasonNumber,
this.showId,
this.stillPath,
this.voteAverage,
this.voteCount,
});
factory TEpisodeToAir.fromJson(Map<String, dynamic> json) => TEpisodeToAir(
airDate: DateTime.parse(json["air_date"]),
episodeNumber: json["episode_number"],
id: json["id"],
name: json["name"],
overview: json["overview"],
productionCode: json["production_code"],
seasonNumber: json["season_number"],
showId: json["show_id"],
stillPath: json["still_path"],
voteAverage: json["vote_average"].toDouble(),
voteCount: json["vote_count"],
);
Map<String, dynamic> toJson() => {
"air_date":
"${airDate.year.toString().padLeft(4, '0')}-${airDate.month.toString().padLeft(2, '0')}-${airDate.day.toString().padLeft(2, '0')}",
"episode_number": episodeNumber,
"id": id,
"name": name,
"overview": overview,
"production_code": productionCode,
"season_number": seasonNumber,
"show_id": showId,
"still_path": stillPath,
"vote_average": voteAverage,
"vote_count": voteCount,
};
}
class Network {
String name;
int id;
String logoPath;
String originCountry;
Network({
this.name,
this.id,
this.logoPath,
this.originCountry,
});
factory Network.fromJson(Map<String, dynamic> json) => Network(
name: json["name"],
id: json["id"],
logoPath: json["logo_path"] == null ? null : json["logo_path"],
originCountry: json["origin_country"],
);
Map<String, dynamic> toJson() => {
"name": name,
"id": id,
"logo_path": logoPath == null ? null : logoPath,
"origin_country": originCountry,
};
}
class Season {
DateTime airDate;
int episodeCount;
int id;
String name;
String overview;
String posterPath;
int seasonNumber;
Season({
this.airDate,
this.episodeCount,
this.id,
this.name,
this.overview,
this.posterPath,
this.seasonNumber,
});
factory Season.fromJson(Map<String, dynamic> json) => Season(
airDate: DateTime.parse(json["air_date"]),
episodeCount: json["episode_count"],
id: json["id"],
name: json["name"],
overview: json["overview"],
posterPath: json["poster_path"],
seasonNumber: json["season_number"],
);
Map<String, dynamic> toJson() => {
"air_date":
"${airDate.year.toString().padLeft(4, '0')}-${airDate.month.toString().padLeft(2, '0')}-${airDate.day.toString().padLeft(2, '0')}",
"episode_count": episodeCount,
"id": id,
"name": name,
"overview": overview,
"poster_path": posterPath,
"season_number": seasonNumber,
};
}
When I tried to catch the error with :
if (snapshot.hasError) {
print('ERROR : ${snapshot.error}');
}
I got this :
I/flutter (16719): ERROR : NoSuchMethodError: The method '[]' was
called on null. I/flutter (16719): Receiver: null I/flutter (16719):
Tried calling: []("air_date")
It could be because the "next_episode_to_air" parameter in the second link (TV show details 2) is actually a null value! You can check for nulls using ?? operator in Dart.
You can have a look at its usage here
In your case, you could use it like this in your TVShow.fromJson method,
nextEpisodeToAir: TEpisodeToAir.fromJson(json["next_episode_to_air"] ?? <your-default-value>),
This will check your code for the value of json["next_episode_to_air"] and put an your default value at it's place if it turns out to be null. You can then deal with this default (or maybe null) value accordingly in your code later.
I have solved the issue with null case handling.In 2nd response, response with key next_episode_to_air is null. Due to this getting error, accessing key on null.
Just handle the possible case for data, currently at factory TVShow.fromJson i.e.
nextEpisodeToAir: json["next_episode_to_air"] == null ? null : TEpisodeToAir.fromJson(json["next_episode_to_air"])

NoSuchMethodError: The method 'map' was called on null

[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method 'map' was called on null.
E/flutter (19718): Receiver: null
E/flutter (19718): Tried calling: map(Closure: (dynamic) => SeriesNo)
I tried json_annotation and json Serieizable but don't work.According my model one.json is ok.but two.json is reques error happen as title.How to solve.I known series no is error but i have no idea how to solve.
This is one.json
{
"bookDetail": {
"title": "aaa",
"author": "aaa",
"image": "https://",
"text": "aaa",
"series_no": [
{
"id": 2
}
],
"created_at": "2019-08-27 15:19:10"
}
}
This is two.json
{
"bookDetail": {
"title": "Test",
"author": "TEst",
"image": "https:/riv19q9x.png",
"text": "Test",
"series_no": null,
"created_at": "2019-08-27 15:13:56"
}
}
This is detail.model using bloc flutter
class BookDetailModel {
BookDetail bookDetail;
BookDetailModel({
this.bookDetail,
});
factory BookDetailModel.fromJson(Map<String, dynamic> json) =>
new BookDetailModel(
bookDetail: BookDetail.fromJson(json["bookDetail"]),
);
Map<String, dynamic> toJson() => {
"bookDetail": bookDetail.toJson(),
};
}
#JsonSerializable(nullable: true)
class BookDetail {
String title;
String author;
String image;
String text;
List<SeriesNo> seriesNo;
DateTime createdAt;
BookDetail({
this.title,
this.author,
this.image,
this.text,
this.seriesNo,
this.createdAt,
});
factory BookDetail.fromJson(Map<String, dynamic> json) => new BookDetail(
title: json["title"],
author: json["author"],
image: json["image"],
text: json["text"],
seriesNo: new List<SeriesNo>.from(
json["series_no"].map((x) => SeriesNo.fromJson(x))),
createdAt: DateTime.parse(json["created_at"]),
);
Map<String, dynamic> toJson() => {
"title": title,
"author": author,
"image": image,
"text": text,
"series_no": new List<dynamic>.from(seriesNo.map((x) => x.toJson())),
"created_at": createdAt.toIso8601String(),
};
}
#JsonSerializable(nullable: true)
class SeriesNo {
int id;
SeriesNo({
this.id,
});
factory SeriesNo.fromJson(Map<String, dynamic> json) => new SeriesNo(
id: json["id"],
);
Map<String, dynamic> toJson() => {
"id": id,
};
}
Try to verify if is not null before:
seriesNo: json["series_no"] != null ? new List<SeriesNo>.from( json["series_no"].map((x) => SeriesNo.fromJson(x))) : List<SeriesNo>().
This is answer for my question.Crd #Stel
try placing seriesNo as dynamic and placing the remaining fields
class BookDetailModel {
BookDetail bookDetail;
BookDetailModel({
this.bookDetail,
});
factory BookDetailModel.fromJson(Map<String, dynamic> json) => BookDetailModel(
bookDetail: BookDetail.fromJson(json["bookDetail"]),
);
Map<String, dynamic> toJson() => {
"bookDetail": bookDetail.toJson(),
};
}
class BookDetail {
String title;
String author;
String image;
String text;
dynamic seriesNo;
DateTime createdAt;
BookDetail({
this.title,
this.author,
this.image,
this.text,
this.seriesNo,
this.createdAt,
});
factory BookDetail.fromJson(Map<String, dynamic> json) => BookDetail(
title: json["title"],
author: json["author"],
image: json["image"],
text: json["text"],
seriesNo: json["series_no"],
createdAt: DateTime.parse(json["created_at"]),
);
Map<String, dynamic> toJson() => {
"title": title,
"author": author,
"image": image,
"text": text,
"series_no": seriesNo,
"created_at": createdAt.toIso8601String(),
};
}
If it's a List and a double value, how can it be written even if it's correct? I got this problem. Please see my link.Link Linkclass
Food _$FoodFromJson(Map<String, dynamic> json) => Food(
ingredient: (json['ingredient'] as List<dynamic>)
.map((e) => e as String)
.toList(),
quantity:
(json['quantity'] as List<dynamic>).map((e) => e as String).toList(),
uom: (json['uom'] as List<dynamic>).map((e) => e as String).toList(),
step: (json['step'] as List<dynamic>).map((e) => e as String).toList(),
);