I am trying to fetch data from the API but when I parse data through fromjson then data is not returning please fix this issue.
this is Function calling API and having issue in this function when I am parsing data through model. I have given code of service class in which i am using API to fetch data of inventory and i have given modal class and json response through API
Future<List<Inventory>> requestInventory(
String accessToken, String userId) async {
final response = await http.get(Uri.parse('${AppUrl.getInventory}/$userId'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer $accessToken'
});
late List<Inventory> list=[];
// List<Inventory>? list;
if (response.statusCode == 200) {
var value = jsonDecode(response.body);
//old
// var data = value['data']['inventory'];
var data = value['details']['data']['user']['inventory'];
print("data in inventory service ->>>> $data");
if (data != null || data != []) {
list= data.map<Inventory>((json) => Inventory.fromJson(json)).toList();
print('inventory service list is ::::::::::::::::::::::: $list');
return list;
} else {
return list = [];
}
// list = data.map<Inventory>((json) => Inventory.fromJson(json)).toList();
// return list;
} else {
return list = [];
}
}
This is my My Model Class
class GetInventory {
GetInventory({
String? details,
Data? data,}){
_details = details;
_data = data;
}
GetInventory.fromJson(dynamic json) {
_details = json['details'];
_data = json['data'] != null ? Data.fromJson(json['data']) : null;
}
String? _details;
Data? _data;
GetInventory copyWith({ String? details,
Data? data,
}) => GetInventory( details: details ?? _details,
data: data ?? _data,
);
String? get details => _details;
Data? get data => _data;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['details'] = _details;
if (_data != null) {
map['data'] = _data?.toJson();
}
return map;
}
}
class Data {
Data({
User? user,
List<Posts>? posts,}){
_user = user;
_posts = posts;
}
Data.fromJson(dynamic json) {
_user = json['user'] != null ? User.fromJson(json['user']) : null;
if (json['posts'] != null) {
_posts = [];
json['posts'].forEach((v) {
_posts?.add(Posts.fromJson(v));
});
}
}
User? _user;
List<Posts>? _posts;
Data copyWith({ User? user,
List<Posts>? posts,
}) => Data( user: user ?? _user,
posts: posts ?? _posts,
);
User? get user => _user;
List<Posts>? get posts => _posts;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
if (_user != null) {
map['user'] = _user?.toJson();
}
if (_posts != null) {
map['posts'] = _posts?.map((v) => v.toJson()).toList();
}
return map;
}
}
class Posts {
Posts({
List<TradeWithPictures>? tradeWithPictures,
List<String>? tags,
List<Pictures>? pictures,
List<Comments>? comments,
String? id,
String? title,
String? description,
String? category,
String? subCategory,
String? condition,
String? user,
String? createdAt,
String? updatedAt,}){
_tradeWithPictures = tradeWithPictures;
_tags = tags;
_pictures = pictures;
_comments = comments;
_id = id;
_title = title;
_description = description;
_category = category;
_subCategory = subCategory;
_condition = condition;
_user = user;
_createdAt = createdAt;
_updatedAt = updatedAt;
}
Posts.fromJson(dynamic json) {
if (json['tradeWithPictures'] != null) {
_tradeWithPictures = [];
json['tradeWithPictures'].forEach((v) {
_tradeWithPictures?.add(TradeWithPictures.fromJson(v));
});
}
_tags = json['tags'] != null ? json['tags'].cast<String>() : [];
if (json['pictures'] != null) {
_pictures = [];
json['pictures'].forEach((v) {
_pictures?.add(Pictures.fromJson(v));
});
}
if (json['comments'] != null) {
_comments = [];
json['comments'].forEach((v) {
_comments?.add(Comments.fromJson(v));
});
}
_id = json['_id'];
_title = json['title'];
_description = json['description'];
_category = json['category'];
_subCategory = json['subCategory'];
_condition = json['condition'];
_user = json['user'];
_createdAt = json['createdAt'];
_updatedAt = json['updatedAt'];
}
List<TradeWithPictures>? _tradeWithPictures;
List<String>? _tags;
List<Pictures>? _pictures;
List<Comments>? _comments;
String? _id;
String? _title;
String? _description;
String? _category;
String? _subCategory;
String? _condition;
String? _user;
String? _createdAt;
String? _updatedAt;
Posts copyWith({ List<TradeWithPictures>? tradeWithPictures,
List<String>? tags,
List<Pictures>? pictures,
List<Comments>? comments,
String? id,
String? title,
String? description,
String? category,
String? subCategory,
String? condition,
String? user,
String? createdAt,
String? updatedAt,
}) => Posts( tradeWithPictures: tradeWithPictures ?? _tradeWithPictures,
tags: tags ?? _tags,
pictures: pictures ?? _pictures,
comments: comments ?? _comments,
id: id ?? _id,
title: title ?? _title,
description: description ?? _description,
category: category ?? _category,
subCategory: subCategory ?? _subCategory,
condition: condition ?? _condition,
user: user ?? _user,
createdAt: createdAt ?? _createdAt,
updatedAt: updatedAt ?? _updatedAt,
);
List<TradeWithPictures>? get tradeWithPictures => _tradeWithPictures;
List<String>? get tags => _tags;
List<Pictures>? get pictures => _pictures;
List<Comments>? get comments => _comments;
String? get id => _id;
String? get title => _title;
String? get description => _description;
String? get category => _category;
String? get subCategory => _subCategory;
String? get condition => _condition;
String? get user => _user;
String? get createdAt => _createdAt;
String? get updatedAt => _updatedAt;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
if (_tradeWithPictures != null) {
map['tradeWithPictures'] = _tradeWithPictures?.map((v) => v.toJson()).toList();
}
map['tags'] = _tags;
if (_pictures != null) {
map['pictures'] = _pictures?.map((v) => v.toJson()).toList();
}
if (_comments != null) {
map['comments'] = _comments?.map((v) => v.toJson()).toList();
}
map['_id'] = _id;
map['title'] = _title;
map['description'] = _description;
map['category'] = _category;
map['subCategory'] = _subCategory;
map['condition'] = _condition;
map['user'] = _user;
map['createdAt'] = _createdAt;
map['updatedAt'] = _updatedAt;
return map;
}
}
class Comments {
Comments({
String? text,
Profile? profile,}){
_text = text;
_profile = profile;
}
Comments.fromJson(dynamic json) {
_text = json['text'];
_profile = json['profile'] != null ? Profile.fromJson(json['profile']) : null;
}
String? _text;
Profile? _profile;
Comments copyWith({ String? text,
Profile? profile,
}) => Comments( text: text ?? _text,
profile: profile ?? _profile,
);
String? get text => _text;
Profile? get profile => _profile;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['text'] = _text;
if (_profile != null) {
map['profile'] = _profile?.toJson();
}
return map;
}
}
class Profile {
Profile({
String? role,
bool? banned,
dynamic bannedTill,
List<dynamic>? inventory,
String? fcmToken,
String? profilePictureURL,
String? id,
String? createdAt,
String? updatedAt,
String? firstName,
String? lastName,}){
_role = role;
_banned = banned;
_bannedTill = bannedTill;
_inventory = inventory;
_fcmToken = fcmToken;
_profilePictureURL = profilePictureURL;
_id = id;
_createdAt = createdAt;
_updatedAt = updatedAt;
_firstName = firstName;
_lastName = lastName;
}
Profile.fromJson(dynamic json) {
_role = json['role'];
_banned = json['banned'];
_bannedTill = json['bannedTill'];
if (json['inventory'] != null) {
_inventory = [];
json['inventory'].forEach((v) {
// _inventory?.add(dynamic.fromJson(v));
});
}
_fcmToken = json['fcmToken'];
_profilePictureURL = json['profilePictureURL'];
_id = json['_id'];
_createdAt = json['createdAt'];
_updatedAt = json['updatedAt'];
_firstName = json['firstName'];
_lastName = json['lastName'];
}
String? _role;
bool? _banned;
dynamic _bannedTill;
List<dynamic>? _inventory;
String? _fcmToken;
String? _profilePictureURL;
String? _id;
String? _createdAt;
String? _updatedAt;
String? _firstName;
String? _lastName;
Profile copyWith({ String? role,
bool? banned,
dynamic bannedTill,
List<dynamic>? inventory,
String? fcmToken,
String? profilePictureURL,
String? id,
String? createdAt,
String? updatedAt,
String? firstName,
String? lastName,
}) => Profile( role: role ?? _role,
banned: banned ?? _banned,
bannedTill: bannedTill ?? _bannedTill,
inventory: inventory ?? _inventory,
fcmToken: fcmToken ?? _fcmToken,
profilePictureURL: profilePictureURL ?? _profilePictureURL,
id: id ?? _id,
createdAt: createdAt ?? _createdAt,
updatedAt: updatedAt ?? _updatedAt,
firstName: firstName ?? _firstName,
lastName: lastName ?? _lastName,
);
String? get role => _role;
bool? get banned => _banned;
dynamic get bannedTill => _bannedTill;
List<dynamic>? get inventory => _inventory;
String? get fcmToken => _fcmToken;
String? get profilePictureURL => _profilePictureURL;
String? get id => _id;
String? get createdAt => _createdAt;
String? get updatedAt => _updatedAt;
String? get firstName => _firstName;
String? get lastName => _lastName;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['role'] = _role;
map['banned'] = _banned;
map['bannedTill'] = _bannedTill;
if (_inventory != null) {
map['inventory'] = _inventory?.map((v) => v.toJson()).toList();
}
map['fcmToken'] = _fcmToken;
map['profilePictureURL'] = _profilePictureURL;
map['_id'] = _id;
map['createdAt'] = _createdAt;
map['updatedAt'] = _updatedAt;
map['firstName'] = _firstName;
map['lastName'] = _lastName;
return map;
}
}
class Pictures {
Pictures({
String? publicID,
String? url,}){
_publicID = publicID;
_url = url;
}
Pictures.fromJson(dynamic json) {
_publicID = json['publicID'];
_url = json['url'];
}
String? _publicID;
String? _url;
Pictures copyWith({ String? publicID,
String? url,
}) => Pictures( publicID: publicID ?? _publicID,
url: url ?? _url,
);
String? get publicID => _publicID;
String? get url => _url;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['publicID'] = _publicID;
map['url'] = _url;
return map;
}
}
/// publicID : "bartermade/post-pictures/oqzvs8cnioj2yncpembd"
/// url : "https://res.cloudinary.com/dtksvfjsi/image/upload/v1649202575/bartermade/post-pictures/oqzvs8cnioj2yncpembd.jpg"
class TradeWithPictures {
TradeWithPictures({
String? publicID,
String? url,}){
_publicID = publicID;
_url = url;
}
TradeWithPictures.fromJson(dynamic json) {
_publicID = json['publicID'];
_url = json['url'];
}
String? _publicID;
String? _url;
TradeWithPictures copyWith({ String? publicID,
String? url,
}) => TradeWithPictures( publicID: publicID ?? _publicID,
url: url ?? _url,
);
String? get publicID => _publicID;
String? get url => _url;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['publicID'] = _publicID;
map['url'] = _url;
return map;
}
}
class User {
User({
String? role,
bool? banned,
dynamic bannedTill,
List<Inventory>? inventory,
dynamic fcmToken,
String? profilePictureURL,
String? id,
String? createdAt,
String? updatedAt,
String? firstName,
String? lastName,}){
_role = role;
_banned = banned;
_bannedTill = bannedTill;
_inventory = inventory;
_fcmToken = fcmToken;
_profilePictureURL = profilePictureURL;
_id = id;
_createdAt = createdAt;
_updatedAt = updatedAt;
_firstName = firstName;
_lastName = lastName;
}
User.fromJson(dynamic json) {
_role = json['role'];
_banned = json['banned'];
_bannedTill = json['bannedTill'];
if (json['inventory'] != null) {
_inventory = [];
json['inventory'].forEach((v) {
_inventory?.add(Inventory.fromJson(v));
});
}
_fcmToken = json['fcmToken'];
_profilePictureURL = json['profilePictureURL'];
_id = json['_id'];
_createdAt = json['createdAt'];
_updatedAt = json['updatedAt'];
_firstName = json['firstName'];
_lastName = json['lastName'];
}
String? _role;
bool? _banned;
dynamic _bannedTill;
List<Inventory>? _inventory;
dynamic _fcmToken;
String? _profilePictureURL;
String? _id;
String? _createdAt;
String? _updatedAt;
String? _firstName;
String? _lastName;
User copyWith({ String? role,
bool? banned,
dynamic bannedTill,
List<Inventory>? inventory,
dynamic fcmToken,
String? profilePictureURL,
String? id,
String? createdAt,
String? updatedAt,
String? firstName,
String? lastName,
}) => User( role: role ?? _role,
banned: banned ?? _banned,
bannedTill: bannedTill ?? _bannedTill,
inventory: inventory ?? _inventory,
fcmToken: fcmToken ?? _fcmToken,
profilePictureURL: profilePictureURL ?? _profilePictureURL,
id: id ?? _id,
createdAt: createdAt ?? _createdAt,
updatedAt: updatedAt ?? _updatedAt,
firstName: firstName ?? _firstName,
lastName: lastName ?? _lastName,
);
String? get role => _role;
bool? get banned => _banned;
dynamic get bannedTill => _bannedTill;
List<Inventory>? get inventory => _inventory;
dynamic get fcmToken => _fcmToken;
String? get profilePictureURL => _profilePictureURL;
String? get id => _id;
String? get createdAt => _createdAt;
String? get updatedAt => _updatedAt;
String? get firstName => _firstName;
String? get lastName => _lastName;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['role'] = _role;
map['banned'] = _banned;
map['bannedTill'] = _bannedTill;
if (_inventory != null) {
map['inventory'] = _inventory?.map((v) => v.toJson()).toList();
}
map['fcmToken'] = _fcmToken;
map['profilePictureURL'] = _profilePictureURL;
map['_id'] = _id;
map['createdAt'] = _createdAt;
map['updatedAt'] = _updatedAt;
map['firstName'] = _firstName;
map['lastName'] = _lastName;
return map;
}
}
class Inventory {
Inventory({
String? quantity,
String? description,
String? url,}){
_quantity = quantity;
_description = description;
_url = url;
}
Inventory.fromJson(dynamic json) {
_quantity = json['quantity'];
_description = json['description'];
_url = json['url'];
}
String? _quantity;
String? _description;
String? _url;
Inventory copyWith({ String? quantity,
String? description,
String? url,
}) => Inventory( quantity: quantity ?? _quantity,
description: description ?? _description,
url: url ?? _url,
);
String? get quantity => _quantity;
String? get description => _description;
String? get url => _url;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['quantity'] = _quantity;
map['description'] = _description;
map['url'] = _url;
return map;
}
}
and this is Json response
{
"details": "got user successfully",
"data": {
"user": {
"role": "user",
"banned": false,
"bannedTill": null,
"inventory": [
{
"quantity": "0",
"description": "hello",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "mobile",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "helpo ",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "desc",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "descc",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "hellog",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "check blue",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "this is app inventory ",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "fhbbj",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "yuj",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "hello",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "ghb",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "tctcct",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "Saad Ebad",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "vbvhh",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "Saad",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "saas",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "hwhah",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "gbbhh",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "hebsb",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "ndnsn",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "hello brother ",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "hfnfnf",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "ffg",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "ghh",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "hawa hawa",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "gggg",
"url": "http://localhost/api/media/inventory-pictures/undefined"
},
{
"quantity": "0",
"description": "Asif",
"url": "http://localhost/api/media/inventory-pictures/undefined"
}
],
"fcmToken": null,
"profilePictureURL": "https://cdn.luxe.digital/media/2019/09/12090502/business-professional-dress-code-men-style-luxe-digital.jpg",
"_id": "624bac63fbf73b08462af651",
"createdAt": "2022-04-05T02:41:39.754Z",
"updatedAt": "2022-04-10T06:36:37.818Z",
"firstName": "saad",
"lastName": "ebad"
},
"posts": [
{
"tradeWithPictures": [
{
"publicID": "bartermade/post-pictures/oqzvs8cnioj2yncpembd",
"url": "https://res.cloudinary.com/dtksvfjsi/image/upload/v1649202575/bartermade/post-pictures/oqzvs8cnioj2yncpembd.jpg"
}
],
"tags": [
"Camera",
"Mobile",
"Cycles"
],
"pictures": [
{
"publicID": "bartermade/post-pictures/vuepwgaymffwhdvcz3lx",
"url": "https://res.cloudinary.com/dtksvfjsi/image/upload/v1649202573/bartermade/post-pictures/vuepwgaymffwhdvcz3lx.jpg"
}
],
"comments": [
{
"text": "bsbsn",
"profile": {
"role": "user",
"banned": false,
"bannedTill": null,
"inventory": [],
"fcmToken": "",
"profilePictureURL": "https://cdn.luxe.digital/media/2019/09/12090502/business-professional-dress-code-men-style-luxe-digital.jpg",
"_id": "624bac63fbf73b08462af651",
"createdAt": "2022-04-05T02:41:39.754Z",
"updatedAt": "2022-04-06T04:29:06.535Z",
"firstName": "saad",
"lastName": "ebad"
}
}
],
"_id": "624cd591fbf73b08462afb73",
"title": "Infinix",
"description": "Infinix note 8",
"category": "mobiles",
"subCategory": "smart phones",
"condition": "Old",
"user": "624bac63fbf73b08462af651",
"createdAt": "2022-04-05T23:49:37.116Z",
"updatedAt": "2022-04-06T04:33:40.069Z"
}
]
}
}
There is an issue with the keys of the json used to get the inventory list. Try with this:
var data = value['data']['user']['inventory'];
Related
I have the following return from the API (which I can return normally on my main screen!):
[
{
"id": 1,
"obs": "",
"dataVcto": "2022-11-02T00:00:00.000Z",
"valor": 200,
"idTPRD": 1,
"dataLcto": "2022-11-02T00:00:00.000Z",
"status": "A",
"idUSRS": 1,
"dC": "C",
"idCTCT": 1,
"tPRD_Nome": "FRETE",
"uSRS_Nome": "Heugenio",
"cTCT_Nome": "Frete p\/Terceiros"
},
{
"id": 2,
"obs": "Maquina Vilmar",
"dataVcto": "2022-12-01T00:00:00.000Z",
"valor": 300,
"idTPRD": 1,
"dataLcto": "2022-11-05T00:00:00.000Z",
"status": "A",
"idUSRS": 1,
"dC": "C",
"idCTCT": 1,
"tPRD_Nome": "FRETE",
"uSRS_Nome": "Heugenio",
"cTCT_Nome": "Frete p\/Terceiros"
},
{
"id": 5,
"obs": "",
"dataVcto": "2022-12-01T00:00:00.000Z",
"valor": 200,
"idTPRD": 2,
"dataLcto": "2022-11-05T00:00:00.000Z",
"status": "A",
"idUSRS": 1,
"dC": "D",
"idCTCT": 1,
"tPRD_Nome": "OLEO",
"uSRS_Nome": "Heugenio",
"cTCT_Nome": "Frete p\/Terceiros"
}
]
My model class (Automatically generated on a website that creates these classes):
class LancamentosModel {
int? id;
String? obs;
String? dataVcto;
int? valor;
int? idTPRD;
String? dataLcto;
String? status;
int? idUSRS;
String? dC;
int? idCTCT;
String? tPRDNome;
String? uSRSNome;
String? cTCTNome;
LancamentosModel(
{this.id,
this.obs,
this.dataVcto,
this.valor,
this.idTPRD,
this.dataLcto,
this.status,
this.idUSRS,
this.dC,
this.idCTCT,
this.tPRDNome,
this.uSRSNome,
this.cTCTNome});
LancamentosModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
obs = json['obs'];
dataVcto = json['dataVcto'];
valor = json['valor'];
idTPRD = json['idTPRD'];
dataLcto = json['dataLcto'];
status = json['status'];
idUSRS = json['idUSRS'];
dC = json['dC'];
idCTCT = json['idCTCT'];
tPRDNome = json['tPRD_Nome'];
uSRSNome = json['uSRS_Nome'];
cTCTNome = json['cTCT_Nome'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['obs'] = this.obs;
data['dataVcto'] = this.dataVcto;
data['valor'] = this.valor;
data['idTPRD'] = this.idTPRD;
data['dataLcto'] = this.dataLcto;
data['status'] = this.status;
data['idUSRS'] = this.idUSRS;
data['dC'] = this.dC;
data['idCTCT'] = this.idCTCT;
data['tPRD_Nome'] = this.tPRDNome;
data['uSRS_Nome'] = this.uSRSNome;
data['cTCT_Nome'] = this.cTCTNome;
return data;
}
}
When I try to save the data in this listing by the application, I get this exception:
Error: Expected a value of type 'String', but got one of type 'int'
action on the button to save the data:
ElevatedButton(
onPressed: () {
var dados = LancamentosModel(
dataLcto: _dataController.text.toString(),
dataVcto: _vencimentocontroller.text.toString(),
obs: _obsController.text.toString(),
valor: int.tryParse(_valorController.text.toString()),
status: _controller.toString(),
dC: _type.toString(),
uSRSNome: "Felippe",
cTCTNome: "Frete",
tPRDNome: "Óleo",
id: 2,
idCTCT: 1,
idTPRD: 1,
idUSRS: 1
);
salvarDados(dados);
},
salvarDados() method:
Future salvarDados(LancamentosModel dados) async {
var resp = await http.post(
Uri.parse("http://hjsystems.dynns.com:8085/GravaLancamentos"),
headers: {
"Authorization": "Basic *******************"
},
body: dados.toJson());
if (resp.statusCode != 200) Exception("Erro ao salvar");
}
You toJson() method does not actually produce JSON, it just produces a data structure that can be serialized as JSON. That is correct. This is the pattern we use.
But you need to actually serialize it as JSON text:
body: jsonEncode(dados.toJson()),
i have a complex json list in my flutter and i want to return the length of array object's nested list. but it is returning all the lists length.
my json list
{
"clients": [
{
"id": 58,
"name": "mmkmkmk",
"address": "mmakaka",
"tin_no": "9887665",
"status": "0",
"created_at": "2022-10-04T18:32:52.000000Z",
"updated_at": "2022-10-04T18:32:52.000000Z",
"phones": [
{
"id": 43,
"client_id": "58",
"supplier_id": null,
"company_id": null,
"phone_number": "987098709",
"email": "mmk#asd.fv",
"model": "Client",
"category": "Sales",
"created_at": "2022-10-04T18:32:52.000000Z",
"updated_at": "2022-10-04T18:32:52.000000Z"
}
]
},
{
"id": 59,
"name": "Konka33",
"address": "bole33",
"tin_no": "41231343",
"status": "1",
"created_at": "2022-10-04T18:33:54.000000Z",
"updated_at": "2022-10-04T18:33:54.000000Z",
"phones": [
{
"id": 44,
"client_id": "59",
"supplier_id": null,
"company_id": null,
"phone_number": "412313421",
"email": "i34#mail.com",
"model": "Client",
"category": "Manager",
"created_at": "2022-10-04T18:33:54.000000Z",
"updated_at": "2022-10-04T18:33:54.000000Z"
},
{
"id": 45,
"client_id": "59",
"supplier_id": null,
"company_id": null,
"phone_number": "-1780132721",
"email": "b34#bmail.com",
"model": "Client",
"category": "Sales",
"created_at": "2022-10-04T18:33:54.000000Z",
"updated_at": "2022-10-04T18:33:54.000000Z"
}
]
}
}
]
I want to display the selected index phones length.
I'm trying to do that by doing datasList[index].phones!.length but it's returning all of the length of the phones object from all clients phones object. not the index i wanted. how can i display the selected phones length?
client model
class Client {
List<Clients>? clients;
Client({required this.clients});
Client.fromJson(Map<String, dynamic> json) {
if (json['clients'] != null) {
clients = <Clients>[];
json['clients'].forEach((v) {
clients?.add(new Clients.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.clients != null) {
data['clients'] = this.clients!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Clients {
int? id;
String? name;
String? address;
int? tinNo;
int? status;
String? createdAt;
String? updatedAt;
List<Phones>? phones;
Clients(
{this.id,
this.name,
this.address,
this.tinNo,
this.status,
this.createdAt,
this.updatedAt,
this.phones});
Clients.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
address = json['address'];
tinNo = json['tin_no'];
status = json['status'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
if (json['phones'] != null) {
phones = <Phones>[];
json['phones'].forEach((v) {
phones!.add(new Phones.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['address'] = this.address;
data['tin_no'] = this.tinNo;
data['status'] = this.status;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
if (this.phones != null) {
data['phones'] = this.phones!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Phones {
int? id;
int? clientId;
Null? supplierId;
Null? companyId;
int? phoneNumber;
String? email;
String? model;
String? category;
String? createdAt;
String? updatedAt;
Phones(
{this.id,
this.clientId,
this.supplierId,
this.companyId,
this.phoneNumber,
this.email,
this.model,
this.category,
this.createdAt,
this.updatedAt});
Phones.fromJson(Map<String, dynamic> json) {
id = json['id'];
clientId = json['client_id'];
supplierId = json['supplier_id'];
companyId = json['company_id'];
phoneNumber = json['phone_number'];
email = json['email'];
model = json['model'];
category = json['category'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['client_id'] = this.clientId;
data['supplier_id'] = this.supplierId;
data['company_id'] = this.companyId;
data['phone_number'] = this.phoneNumber;
data['email'] = this.email;
data['model'] = this.model;
data['category'] = this.category;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
OrderItem Model Class:
This is my OrderItem Model Class which contains a CartItem Map as I am trying to Parse this I am getting error "type 'List' is not a subtype of type 'Map<String, dynamic>'"
import 'package:flutter/cupertino.dart';
import 'package:practice_app/models/shippingAdress.dart';
import 'package:practice_app/providers/cart_provider.dart';
class OrderItem with ChangeNotifier {
final String? id;
final String? orderNo;
final DateTime? date;
final String? paymentMethod;
final ShippingAdress? shippingAdress;
final Map<String, CartItem>? cartItem;
final int? price;
OrderItem({
this.id,
this.orderNo,
this.date,
this.paymentMethod,
this.shippingAdress,
this.cartItem,
this.price,
});
factory OrderItem.fromJson(Map<String, dynamic> json) {
print('Json:');
print(json);
//tempitems
final json1 = json['order'];
Map<String, CartItem> dd = {};
final temp = CartItem.fromJson(json['order']) as Map<String, CartItem>;
final tempadd = ShippingAdress.fromJson(json['shippingAddress']) as ShippingAdress;
//final map = Map<String, CartItem>.from(temp);
print("printing temp items");
print(temp);
print("temp address");
//print(tempadd);
return OrderItem(
id: json['ProductID'].toString(),
orderNo: json['OrderNO'] ?? '',
date: json['Date'] ?? DateTime.now(),
paymentMethod: json['paymentMethod'] ?? 0,
shippingAdress: tempadd,
cartItem: temp,
price: json["price"] ?? '');
}
CartItem Model Class:
Here is the fromJson Method Define for CartItem.
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class CartItem {
String? id;
String? plantId;
String? title;
num? price;
int? quantity;
String? imageAssets;
String? size;
Color? color;
CartItem({
this.id,
this.plantId,
this.title,
this.price,
this.quantity,
this.imageAssets,
this.size,
this.color,
});
factory CartItem.fromJson(Map<String, dynamic> json) {
return CartItem(
id: json['id'] as String,
plantId: json['plantId'] as String,
title: json['title'] as String,
price: json['price'] as int,
quantity: json['quantity'] as int,
imageAssets: json['imageAsset'] as String,
size: json['size'] as String,
color: json['color'] ?? Colors.green[400] as Color,
);
}
Map toJson() => {
'id': this.id,
'plantId': this.plantId,
'title': this.title,
'price': this.price,
'quantity': this.quantity,
'imageAsset': this.imageAssets,
'size': this.size,
'color': this.color,
};
}
class Cart with ChangeNotifier {
Map<String, CartItem> _item = {};
Map<String, CartItem> get items {
return {..._item};
}
List<CartItem> get cartitem {
return [..._item.values.toList()];
}
int get itemCount {
return _item.length;
}
void emptyCart() {
_item.clear();
notifyListeners();
}
CartItem findById(String id) {
return _item.values.toList().firstWhere((element) => element.id == id);
}
double get totalAmount {
double total = 0.0;
_item.forEach((key, cartItem) {
total += cartItem.price! * cartItem.quantity!;
});
return total;
}
void removeItem(String productId) {
_item.remove(productId);
notifyListeners();
}
void updateCart(String id, CartItem newCart) {
// try {
if (_item.containsKey(id)) {
_item.update(
id,
(value) => CartItem(
plantId: newCart.plantId,
id: newCart.id,
title: newCart.title,
price: newCart.price,
quantity: newCart.quantity,
imageAssets: newCart.imageAssets,
size: newCart.size,
color: newCart.color,
),
);
}
notifyListeners();
// final SharedPreferences prefs = await SharedPreferences.getInstance();
// final cartData = json.encode(
// {
// _item,
// },
// );
// prefs.setString('CartData', cartData);
// } catch (error) {
// throw error;
// }
}
Future<void> addItem(String plantId, String quantity, String title,
double price, String image, String size, Color color) async {
int quantityy = quantity == '' ? 1 : int.parse(quantity);
String sizee = size == 'Small'
? 'Small'
: size == 'Large'
? 'Large'
: size == 'Extra Large'
? 'Extra Large'
: '';
try {
if (_item.containsKey(plantId)) {
//change Quantity
_item.update(
plantId,
(existingCartItem) => CartItem(
plantId: plantId,
id: existingCartItem.id,
title: existingCartItem.title,
price: existingCartItem.price,
imageAssets: existingCartItem.imageAssets,
quantity: existingCartItem.quantity! + quantityy,
size: sizee,
color: color,
),
);
} else {
_item.putIfAbsent(
plantId,
() => CartItem(
plantId: plantId,
id: DateTime.now().toString(),
title: title,
price: price,
imageAssets: image,
quantity: quantityy,
size: sizee,
color: color,
),
);
}
print(plantId);
notifyListeners();
final SharedPreferences prefs = await SharedPreferences.getInstance();
//print(${cartitem.first.});
final cartData = jsonEncode(
{
'cartItem': _item.toString(),
},
);
prefs.setString('CartData', cartData);
print(cartData);
print('Shared done');
} catch (error) {
throw error;
}
}
Future<bool> tryAutoFillCart() async {
final perfs = await SharedPreferences.getInstance();
if (!perfs.containsKey('CartData')) {
return false;
}
final fetchCartData = perfs.getString('CartData');
final extractedCartData =
jsonDecode(fetchCartData!) as Map<String, dynamic>;
_item = extractedCartData['cartItem'] as Map<String, CartItem>;
notifyListeners();
return true;
}
}
API DATA RESPONSE:
This is my Api data response I'm trying to parse specifically the order.
{
"StatusCode": 200,
"StatusMessage": "success",
"ProductID": 20,
"orderNO": 20,
"Date": null,
"paymentMethod": "Visa",
"shippingAddress": {
"ID": "20",
"FullName": "Ali",
"ShippingAddress": "Stadium Road"
},
"order": [
{
"id": "p8",
"plantId": "3",
"title": "Ali",
"imageAsset": "assets/images/plant3.png",
"price": 80,
"size": "Small",
"color": null,
"quantity": 4
},
{
"id": "p8",
"plantId": "3",
"title": "IQBAL",
"imageAsset": "assets/images/plant2.png",
"price": 80,
"size": "Small",
"color": null,
"quantity": 4
}
],
"price": 1500,
"Message": null
}
Error
Error I am getting trying to parse
I'm having a really complex JSON file to parse:
{
"adult": false,
"backdrop_url": "https://image.tmdb.org/t/p/w500/gLbBRyS7MBrmVUNce91Hmx9vzqI.jpg",
"belongs_to_collection": {
"id": 230,
"name": "The Godfather Collection",
"poster_url": "https://image.tmdb.org/t/p/w200/sSbkKCHtIEakht5rnEjrWeR2LLG.jpg",
"backdrop_url": "https://image.tmdb.org/t/p/w500/3WZTxpgscsmoUk81TuECXdFOD0R.jpg"
},
"budget": 13000000,
"genres": [
"Drama",
"Crime"
],
"homepage": null,
"id": 240,
"imdb_id": "tt0071562",
"original_language": "en",
"original_title": "The Godfather: Part II",
"overview": "In the continuing saga of the Corleone crime family, a young Vito Corleone grows up in Sicily and in 1910s New York. In the 1950s, Michael Corleone attempts to expand the family business into Las Vegas, Hollywood and Cuba.",
"popularity": 17.578,
"poster_url": "https://image.tmdb.org/t/p/w200/bVq65huQ8vHDd1a4Z37QtuyEvpA.jpg",
"production_companies": [
{
"id": 4,
"logo_url": "https://image.tmdb.org/t/p/w200/fycMZt242LVjagMByZOLUGbCvv3.png",
"name": "Paramount",
"origin_country": "US"
},
{
"id": 536,
"logo_url": null,
"name": "The Coppola Company",
"origin_country": ""
}
],
"production_countries": [
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "1974-12-20",
"revenue": 102600000,
"runtime": 200,
"spoken_languages": [
{
"iso_639_1": "en",
"name": "English"
},
{
"iso_639_1": "it",
"name": "Italiano"
},
{
"iso_639_1": "la",
"name": "Latin"
},
{
"iso_639_1": "es",
"name": "Español"
}
],
"status": "Released",
"tagline": "I don't feel I have to wipe everybody out, Tom. Just my enemies.",
"title": "The Godfather: Part II",
"video": false,
"vote_average": 8.5,
"vote_count": 4794
}
And this is my class for parsing:
class movieDetails {
bool? adult;
String? backdropUrl;
Null? belongsToCollection;
int? budget;
List<String>? genres;
Null? homepage;
int? id;
String? imdbId;
String? originalLanguage;
String? originalTitle;
String? overview;
double? popularity;
String? posterUrl;
List<ProductionCompanies>? productionCompanies;
List<ProductionCountries>? productionCountries;
String? releaseDate;
int? revenue;
int? runtime;
List<SpokenLanguages>? spokenLanguages;
String? status;
String? tagline;
String? title;
bool? video;
double? voteAverage;
int? voteCount;
movieDetails(
{this.adult,
this.backdropUrl,
this.belongsToCollection,
this.budget,
this.genres,
this.homepage,
this.id,
this.imdbId,
this.originalLanguage,
this.originalTitle,
this.overview,
this.popularity,
this.posterUrl,
this.productionCompanies,
this.productionCountries,
this.releaseDate,
this.revenue,
this.runtime,
this.spokenLanguages,
this.status,
this.tagline,
this.title,
this.video,
this.voteAverage,
this.voteCount});
movieDetails.fromJson(Map<String, dynamic> json) {
adult = json['adult'];
backdropUrl = json['backdrop_url'];
belongsToCollection = json['belongs_to_collection'];
budget = json['budget'];
genres = json['genres'].cast<String>();
homepage = json['homepage'];
id = json['id'];
imdbId = json['imdb_id'];
originalLanguage = json['original_language'];
originalTitle = json['original_title'];
overview = json['overview'];
popularity = json['popularity'];
posterUrl = json['poster_url'];
if (json['production_companies'] != null) {
productionCompanies = <ProductionCompanies>[];
json['production_companies'].forEach((v) {
productionCompanies!.add(new ProductionCompanies.fromJson(v));
});
}
if (json['production_countries'] != null) {
productionCountries = <ProductionCountries>[];
json['production_countries'].forEach((v) {
productionCountries!.add(new ProductionCountries.fromJson(v));
});
}
releaseDate = json['release_date'];
revenue = json['revenue'];
runtime = json['runtime'];
if (json['spoken_languages'] != null) {
spokenLanguages = <SpokenLanguages>[];
json['spoken_languages'].forEach((v) {
spokenLanguages!.add(new SpokenLanguages.fromJson(v));
});
}
status = json['status'];
tagline = json['tagline'];
title = json['title'];
video = json['video'];
voteAverage = json['vote_average'];
voteCount = json['vote_count'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['adult'] = this.adult;
data['backdrop_url'] = this.backdropUrl;
data['belongs_to_collection'] = this.belongsToCollection;
data['budget'] = this.budget;
data['genres'] = this.genres;
data['homepage'] = this.homepage;
data['id'] = this.id;
data['imdb_id'] = this.imdbId;
data['original_language'] = this.originalLanguage;
data['original_title'] = this.originalTitle;
data['overview'] = this.overview;
data['popularity'] = this.popularity;
data['poster_url'] = this.posterUrl;
if (this.productionCompanies != null) {
data['production_companies'] =
this.productionCompanies!.map((v) => v.toJson()).toList();
}
if (this.productionCountries != null) {
data['production_countries'] =
this.productionCountries!.map((v) => v.toJson()).toList();
}
data['release_date'] = this.releaseDate;
data['revenue'] = this.revenue;
data['runtime'] = this.runtime;
if (this.spokenLanguages != null) {
data['spoken_languages'] =
this.spokenLanguages!.map((v) => v.toJson()).toList();
}
data['status'] = this.status;
data['tagline'] = this.tagline;
data['title'] = this.title;
data['video'] = this.video;
data['vote_average'] = this.voteAverage;
data['vote_count'] = this.voteCount;
return data;
}
}
class ProductionCompanies {
int? id;
String? logoUrl;
String? name;
String? originCountry;
ProductionCompanies({this.id, this.logoUrl, this.name, this.originCountry});
ProductionCompanies.fromJson(Map<String, dynamic> json) {
id = json['id'];
logoUrl = json['logo_url'];
name = json['name'];
originCountry = json['origin_country'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['logo_url'] = this.logoUrl;
data['name'] = this.name;
data['origin_country'] = this.originCountry;
return data;
}
}
class ProductionCountries {
String? iso31661;
String? name;
ProductionCountries({this.iso31661, this.name});
ProductionCountries.fromJson(Map<String, dynamic> json) {
iso31661 = json['iso_3166_1'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['iso_3166_1'] = this.iso31661;
data['name'] = this.name;
return data;
}
}
class SpokenLanguages {
String? iso6391;
String? name;
SpokenLanguages({this.iso6391, this.name});
SpokenLanguages.fromJson(Map<String, dynamic> json) {
iso6391 = json['iso_639_1'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['iso_639_1'] = this.iso6391;
data['name'] = this.name;
return data;
}
}
Since I'm getting this JSON from the internet, here's the fetching method:
Future<movieDetails> fetchDetails() async {
final response = await http.get(Uri.parse(url)); //url: just a string containing the website's URL
if (response.statusCode == 200){
return compute(parseDetails, response.body);
}
else{
throw Exception('Failed!');
}
}
Everything seems okay from here, but then I have literally no idea how to do the parseDetails function. How should I do it? This JSON file is too complex for me to handle.
Is there any reason you're using compute to parse the JSON file? The file you provided seems to have reasonable length and won't block the main isolate (unless the file is much bigger than what you provided, where compute might be appropriate)
Your code will be something like this (will parse the JSON response in the main isolate). For more details see the official documentation about JSON. Also a tip, follow the dart naming convention PascalCase for classes (MovieDetails instead of movieDetails)
Future<movieDetails> fetchDetails() async {
final response = await http.get(Uri.parse(url)); //url: just a string containing the website's URL
if (response.statusCode == 200){
Map<String, dynamic> movieDetailsMap = jsonDecode(response.body);
return movieDetails.fromJson(movieDetailsMap);
}
else{
throw Exception('Failed!');
}
}
movieDetails parseDetails(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return movieDetails.fromJson(parsed);
}
I'm trying to parse an object in JSON and I am able to do so successfully without the nested JSON object Opening Hours. I don't know why. Here is the json data:
{
"location": [
{
"id": 4,
"location_name": "PastryMan",
"cbd_products": "",
"phone": "1231231234",
"street_address": "535 7th Ave",
"location_logo": "https://.s3.amazonaws.com/location_logo/water.png",
"location_photo": "https://dispensaries.s3.amazonaws.com/location_photo/delta9.jpg",
"sponsored_location": "Yes",
"city": "New York",
"state": "New York",
"zip_Code": 10018,
"lat": 40.7538935555556,
"lng": -73.9883851111111,
"latlng": "(40.7770112244898, -74.2110798163265)",
"opening_hours": [
{
"day_of_week": "Tuesday",
"opening_time": "08:00:00",
"closing_time": "22:00:00"
},
{
"day_of_week": "Wednesday",
"opening_time": "08:00:00",
"closing_time": "22:00:00"
},
{
"day_of_week": "Thursday",
"opening_time": "08:00:00",
"closing_time": "22:00:00"
},
{
"day_of_week": "Friday",
"opening_time": "08:00:00",
"closing_time": "22:00:00"
},
{
"day_of_week": "Saturday",
"opening_time": "08:00:00",
"closing_time": "22:00:00"
},
{
"day_of_week": "Sunday",
"opening_time": "08:00:00",
"closing_time": "22:00:00"
},
{
"day_of_week": 7,
"opening_time": "08:00:00",
"closing_time": "22:00:00"
}
],
"ratings": 0.0
},}
I have setup my class like this:
class Location {
int id;
String name;
String phone;
String address;
String city;
String locationPhoto;
String locationLogo;
String state;
num lat;
num long;
List<OpeningHours> openingHours;
String cbdProducts;
num rating;
String zipCode;
String latlng;
String sponsored;
location(
{this.id,
this.name,
this.cbdProducts,
this.phone,
this.address,
this.locationLogo,
this.locationPhoto,
this.sponsored,
this.city,
this.state,
this.zipCode,
this.lat,
this.long,
this.latlng,
this.openingHours,
this.rating});
location.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['location_name'];
cbdProducts = json['cbd_products'];
phone = json['phone'];
address = json['street_address'];
locationLogo = json['location_logo'];
locationPhoto = json['location_photo'];
address = json['sponsored_location'];
city = json['city'];
state = json['state'];
zipCode = json['zip_Code'];
lat = json['lat'];
long = json['long'];
latlng = json['latlng'];
if (json['opening_hours'] != null) {
openingHours = new List<OpeningHours>();
json['opening_hours'].forEach((v) {
openingHours.add(new OpeningHours.fromJson(v));
});
}
rating = json['ratings'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['location_name'] = this.name;
data['cbd_products'] = this.cbdProducts;
data['phone'] = this.phone;
data['street_address'] = this.address;
data['location_logo'] = this.locationLogo;
data['location_photo'] = this.locationPhoto;
data['sponsored_location'] = this.address;
data['city'] = this.city;
data['state'] = this.state;
data['zip_Code'] = this.zipCode;
data['lat'] = this.lat;
data['lng'] = this.long;
data['latlng'] = this.latlng;
if (this.openingHours != null) {
data['opening_hours'] = this.openingHours.map((v) => v.toJson()).toList();
}
data['ratings'] = this.rating;
return data;
}
}
class OpeningHours {
String dayOfWeek;
String openingTime;
String closingTime;
OpeningHours({this.dayOfWeek, this.openingTime, this.closingTime});
OpeningHours.fromJson(Map<String, dynamic> json) {
dayOfWeek = json['day_of_week'];
openingTime = json['opening_time'];
closingTime = json['closing_time'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['day_of_week'] = this.dayOfWeek;
data['opening_time'] = this.openingTime;
data['closing_time'] = this.closingTime;
return data;
}
}
Then I call my api in a future to get the details. Here is the api:
Future getLocations() async {
var url = '$_server/api/customer/location/';
HttpClient client = new HttpClient();
HttpClientRequest request = await client.getUrl(Uri.parse(url));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
var responseData = json.decode(reply);
Locations _location = Locations.fromJson(responseData);
currentLocations = _location.location;
print(currentLocations);
return _location.location;
}
When I call the api currentLocations = null. What have I done wrong here?
One of the easiest ways is to use quicktype.io to generate PODO (Plain Old Dart Objects). Just Select the dart language to create PODO and copy-paste your JSON over there and provide the class Name as "Location". I have done that for you now your location class will look like this:
class Location {
Location({
this.location,
});
List<LocationElement> location;
factory Location.fromJson(Map<String, dynamic> json) => Location(
location: List<LocationElement>.from(json["location"].map((x) => LocationElement.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"location": List<dynamic>.from(location.map((x) => x.toJson())),
};
}
class LocationElement {
LocationElement({
this.id,
this.locationName,
this.cbdProducts,
this.phone,
this.streetAddress,
this.locationLogo,
this.locationPhoto,
this.sponsoredLocation,
this.city,
this.state,
this.zipCode,
this.lat,
this.lng,
this.latlng,
this.openingHours,
this.ratings,
});
int id;
String locationName;
String cbdProducts;
String phone;
String streetAddress;
String locationLogo;
String locationPhoto;
String sponsoredLocation;
String city;
String state;
int zipCode;
double lat;
double lng;
String latlng;
List<OpeningHour> openingHours;
int ratings;
factory LocationElement.fromJson(Map<String, dynamic> json) => LocationElement(
id: json["id"],
locationName: json["location_name"],
cbdProducts: json["cbd_products"],
phone: json["phone"],
streetAddress: json["street_address"],
locationLogo: json["location_logo"],
locationPhoto: json["location_photo"],
sponsoredLocation: json["sponsored_location"],
city: json["city"],
state: json["state"],
zipCode: json["zip_Code"],
lat: json["lat"].toDouble(),
lng: json["lng"].toDouble(),
latlng: json["latlng"],
openingHours: List<OpeningHour>.from(json["opening_hours"].map((x) => OpeningHour.fromJson(x))),
ratings: json["ratings"],
);
Map<String, dynamic> toJson() => {
"id": id,
"location_name": locationName,
"cbd_products": cbdProducts,
"phone": phone,
"street_address": streetAddress,
"location_logo": locationLogo,
"location_photo": locationPhoto,
"sponsored_location": sponsoredLocation,
"city": city,
"state": state,
"zip_Code": zipCode,
"lat": lat,
"lng": lng,
"latlng": latlng,
"opening_hours": List<dynamic>.from(openingHours.map((x) => x.toJson())),
"ratings": ratings,
};
}
class OpeningHour {
OpeningHour({
this.dayOfWeek,
this.openingTime,
this.closingTime,
});
dynamic dayOfWeek;
String openingTime;
String closingTime;
factory OpeningHour.fromJson(Map<String, dynamic> json) => OpeningHour(
dayOfWeek: json["day_of_week"],
openingTime: json["opening_time"],
closingTime: json["closing_time"],
);
Map<String, dynamic> toJson() => {
"day_of_week": dayOfWeek,
"opening_time": openingTime,
"closing_time": closingTime,
};
}
This may work now and if still there is issue then you may be getting null value from backend.