Error saving data in Rest API - Flutter/Dart - json

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()),

Related

How to parse a complex JSON file in Flutter

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);
}

Data is not parsing into map through fromJson function

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'];

How to read json array from json response in flutter ? I am new in flutter Please help me

Below is my json response, i want to get this response into model and nested model class. Please help me to read this json. Thanks in advance. I am new in flutter to parse json response in model class.
'''
{
"success": 1,
"totalResults": 5,
"data": [
{
"id": 1,
"bank_name": "SBI bank",
"bank_logo": "http://3.143.33.201/assets/banklogo/1/sbi-round-logo.png",
"bank_desc": "sbi",
"rating": "AA"
},
{
"id": 2,
"bank_name": "Yes bank",
"bank_logo": "http://3.143.33.201/assets/banklogo/2/yes-round-logo.png",
"bank_desc": "Yes bank",
"rating": "AA"
},
{
"id": 3,
"bank_name": "Union bank",
"bank_logo": "http://3.143.33.201/assets/banklogo/3/union-round-logo.png",
"bank_desc": "union bank",
"rating": "AA"
},
{
"id": 9,
"bank_name": "Bank of Baroda",
"bank_logo": "http://3.143.33.201/assets/banklogo/9/bob.png",
"bank_desc": "Bank of Baroda",
"rating": "AA"
},
{
"id": 10,
"bank_name": "IndusInd Bank",
"bank_logo": "http://3.143.33.201/assets/banklogo/10/Indus-bank-2.png",
"bank_desc": "IndusInd Bank",
"rating": "AA"
}
]
}
'''
We have a inbuilt package in dart for it,
dart:convert, the usage is as follows
import 'dart:convert' as convert;
...
// perform your http request and get the response from it,
var responseData = convert.jsonDecode(response.body);
convert.jsonDecode() will enable accessing the data stores in the responseData with key values.
#note : I have imported it as convert as for my convenience as I don't get confused while development.
Happy coding
You can use JSON and serialization for this
final _response = jsonDecode(jsonResponse);
After that you can use _response data in your model class like this
YourModel.fromJson(_response);
Initialize your model and use like this
final YourModel _yourModel = YourModel();
final _isSuccess = _yourModel.success;
final _data = _yourModel.data;
Step 1 >
Creat BankDataModel.dart
class BankDataModel {
int? success;
int? totalResults;
List<Data>? data;
BankDataModel({this.success, this.totalResults, this.data});
BankDataModel.fromJson(Map<String, dynamic> json) {
success = json['success'];
totalResults = json['totalResults'];
if (json['data'] != null) {
data = <Data>[];
json['data'].forEach((v) {
data!.add(new Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['success'] = this.success;
data['totalResults'] = this.totalResults;
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
int? id;
String? bankName;
String? bankLogo;
String? bankDesc;
String? rating;
Data({this.id, this.bankName, this.bankLogo, this.bankDesc, this.rating});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
bankName = json['bank_name'];
bankLogo = json['bank_logo'];
bankDesc = json['bank_desc'];
rating = json['rating'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['bank_name'] = this.bankName;
data['bank_logo'] = this.bankLogo;
data['bank_desc'] = this.bankDesc;
data['rating'] = this.rating;
return data;
}
}
Step 2>
Crete Object you want use
BankDataModel _bankDataModel = BankDataModel();
Step 3>
Api call
Future<BankDataModel> getData() async {
BankDataModel _bankDataModel = BankDataModel();
final url = 'your-url';
try {
final response = await client.get(url);
if (response.statusCode == 200) {
_bankDataModel = BankDataModel.fromJson(response.data); < -- Here Json to BankDataModel Convert..
print(_bankDataModel.totalResults.toString()); < -- here print 5 as per question.
return _bankDataModel;
} else {
print(response.statusCode);
throw response.statusCode;
}
} catch (error) {
print(error);
}
}
Thanks you. Happy to help you.

how to get list of keys and list of value from a single json in flutter

i have a json
{
"result": [
{
"id": 2,
"e_id": 2,
"e_name": "0",
"abc": 0,
"doa": "2021-02-15 13:17:11"
},
{
"id": 3,
"e_id": 22,
"e_name": "ok",
"abc": 1,
"doa": "2021-02-15 13:17:57"
}
],
"status": 1,
"msg": "Successfully fetched"
}
.
How i want two list like
List keyList=[
"id","e_id","e_name","abc","doa"];
and
List valueList=[
{
2, 2,"0",0,"2021-02-15 13:17:11"
},
{
3, 22,"ok",1,"2021-02-15 13:17:57"
}
];
anyOne who can help me??
how to get list of keys and list of value, both are separate lists and fetch only from single json which is given above.
here is my model class---
class DataModel {
List<Result> result;
int status;
String msg;
DataModel({this.result, this.status, this.msg});
DataModel.fromJson(Map<String, dynamic> json) {
if (json['result'] != null) {
result = new List<Result>();
json['result'].forEach((v) {
result.add(new Result.fromJson(v));
});
}
status = json['status'];
msg = json['msg'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.result != null) {
data['result'] = this.result.map((v) => v.toJson()).toList();
}
data['status'] = this.status;
data['msg'] = this.msg;
return data;
}
}
class Result {
int id;
int eId;
String eName;
String abc;
String doa;
Result(
{this.id,
this.eId,
this.eName,
this.abc,
this.doa});
Result.fromJson(Map<String, dynamic> json) {
id = json['id'];
eId = json['e_id'];
eName = json['e_name'];
abc= json['abc'];
doa = json['doa'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['e_id'] = this.eId;
data['e_name'] = this.eName;
data['abc'] = this.abc;
data['doa'] = this.doa;
return data;
}
}
i dont need model mapping,
i need only two different list- one is keyList and other one is valuelist form the result.
kindly help me to get this lists
Map<String, dynamic> json ={
"result": [
{
"id": 2,
"e_id": 2,
"e_name": "0",
"abc": 0,
"doa": "2021-02-15 13:17:11"
},
{
"id": 3,
"e_id": 22,
"e_name": "ok",
"abc": 1,
"doa": "2021-02-15 13:17:57"
}
],
"status": 1,
"msg": "Successfully fetched"
};
List<String> keyList;
List<List<dynamic>> valueList = [];
json["result"].forEach((entry) {
keyList ??= entry.keys;
valueList.add(entry.values);
});
Here is the code which gives you key and values as a List:
You can copy and try it out on dartpad.dev
import 'dart:convert';
String json = '''
{
"result": [
{
"id": 2,
"e_id": 2,
"e_name": "0",
"abc": 0,
"doa": "2021-02-15 13:17:11"
},
{
"id": 3,
"e_id": 22,
"e_name": "ok",
"abc": 1,
"doa": "2021-02-15 13:17:57"
}
],
"status": 1,
"msg": "Successfully fetched"
}
''';
void main() {
Map<String, dynamic> map = jsonDecode(json);
List<String> keyList = map['result'][0].keys.toList();
List<dynamic> listOfValues = [];
List<dynamic> valueList = map['result'];
for(int i=0; i < valueList.length; i++) {
Map<String, dynamic> obj = valueList[i];
listOfValues.addAll(obj.values);
}
keyList.forEach(print);
print('\n\n');
listOfValues.forEach(print);
}
Output by printing each element of both arrays:
id
e_id
e_name
abc
doa
2
2
0
0
2021-02-15 13:17:11
3
22
ok
1
2021-02-15 13:17:57
Use rootBundle.loadString('assets/json_file.json');
and then json.decode(jsonString);
Now you can use it normally

How to get json array in Flutter/Dart

I would want to get the data for all "name" only from the array data.
I want to print(data['data']['name']);
But it returns this error:
Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
But when I print(data['data']);, it will return all data from "data":
"data": [
{
"created_at": "2020-03-16 16:10:51",
"deleted_at": null,
"id": 2,
"is_active": 1,
"name": "Maybank",
"updated_at": "2020-03-16 16:18:06"
},
{
"created_at": "2020-03-16 16:27:37",
......
],
Call API Code
displayBanks(BuildContext context) async {
_callApi.refreshTokenApi(context);
var _addressUrl = '$_hostUrl/banks'; //API URL
final SharedPreferences prefs = await SharedPreferences.getInstance();
_accessToken = prefs.getString('access_token');
Response _response = await get(_addressUrl, headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $_accessToken'
});
var data;
data = jsonDecode(_response.body);
if (_response.statusCode == 200) {
print(data['data']['name']);
return data;
}
else {
print(_response.statusCode);
}
}
SAMPLE JSON DATA FROM API URL:
{
"data": [
{
"created_at": "2020-03-16 16:10:51",
"deleted_at": null,
"id": 2,
"is_active": 1,
"name": "Maybank",
"updated_at": "2020-03-16 16:18:06"
},
{
"created_at": "2020-03-16 16:27:37",
"deleted_at": null,
"id": 3,
"is_active": 1,
"name": "India International Bank (Malaysia) Berhad",
"updated_at": "2020-03-16 16:27:37"
},
{
"created_at": "2020-03-16 16:27:37",
"deleted_at": null,
"id": 4,
"is_active": 1,
"name": "National Bank of Abu Dhabi Malaysia Berhad",
"updated_at": "2020-03-16 16:27:37"
}
],
"links": {
"first": "https://demo.local/api/banks?page=1",
"last": "https://demo.local/api/banks?page=1",
"next": null,
"prev": null
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 1,
"path": "https://demo.local/api/banks",
"per_page": 5,
"to": 3,
"total": 3
}
}
Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
The exception message explains the issue clearly.
The property 'name' is inside an object which itself placed in an array. So you first decode the array. Then access each object using the index (0..n), then from each object, you can read the 'name' property.
Here you go
class MyData {
final List<Data> data;
MyData({this.data});
factory MyData.fromJson(Map<String, dynamic> json) {
return MyData(
data: json['data'] != null ? (json['data'] as List).map((i) => Data.fromJson(i)).toList() : null,
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
final String created_at;
final String deleted_at;
final int id;
final int is_active;
final String name;
final String updated_at;
Data({this.created_at, this.deleted_at, this.id, this.is_active, this.name, this.updated_at});
factory Data.fromJson(Map<String, dynamic> json) {
return Data(
created_at: json['created_at'],
deleted_at: json['deleted_at'],
id: json['id'],
is_active: json['is_active'],
name: json['name'],
updated_at: json['updated_at'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['created_at'] = this.created_at;
data['id'] = this.id;
data['is_active'] = this.is_active;
data['name'] = this.name;
data['updated_at'] = this.updated_at;
data['deleted_at'] = this.deleted_at;
return data;
}
}
The error makes sense. The 'data' attribute in your JSON is array. So, you'll have to pass index of the item to access 'name' attribute - something like - data['data'][0]['name'] to get 'Maybank'.
Ideally, you should have a class which creates the instance from the JSON. In this case, the code snippet will look like :
Banks banks = new Banks.fromJson(data)
Now, you can use sites like this to create a class definition (including.fromJson).