NoSuchMethodError: The method 'map' was called on null - json

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

Related

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.

parsing complex json flutter list<map> in list

I have a json response where there is a list that contains a list, then there is a map in it, I tried to parse it but it failed, what kind of error did I do? Previously I used this method to parse the map that was in the list and it worked
response json
{
"status": "success",
"data": [
{
"id_category": 1,
"category_slug": "cc",
"category_name": "Credit Card",
"data_payment": [
{
"payment_slug": "cc",
"payment_name": "Credit Card",
"payment_logo": "https://cdn.xx.id/assets_midtrans/cc.png"
}
]
}
],
"message": "Success Get Data"
}
mycode
class PaymentMethodListModel {
final String status, message;
final List<_Data> data;
PaymentMethodListModel({
this.status,
this.message,
this.data,
});
factory PaymentMethodListModel.fromJson(Map<String, dynamic> x) {
var list = x['data'] as List;
print(list.runtimeType);
List<_Data> sd = list.map((i) => _Data.fromJson(i)).toList();
return PaymentMethodListModel(
status: x['status'],
data: sd,
message: x['message'],
);
}
}
class _Data {
final String categorySlug, categoryName;
final List<DataPayment> dataPayment;
_Data({
this.categorySlug,
this.categoryName,
this.dataPayment,
});
factory _Data.fromJson(Map<String, dynamic> obj) {
var list = obj['data_payment'] as List;
List<DataPayment> dataPaymentList = list.map((i) => DataPayment.fromJson(i)).toList();
return _Data(
categorySlug: obj['category_slug'],
categoryName: obj['category_name'],
dataPayment: dataPaymentList,
);
}
}
class DataPayment {
final String paymentSlug, paymentName, paymentLogo;
DataPayment({
this.paymentSlug,
this.paymentName,
this.paymentLogo,
});
factory DataPayment.fromJson(Map<String, dynamic> x) => DataPayment(
paymentSlug: x['payment_slug'],
paymentName: x['payment_name'],
paymentLogo: x['payment_logo'],
);
}
error message
The method 'map' was called on null.
Receiver: null
Tried calling: map(Closure: (dynamic) => DataPayment)
Try below code
var paymentListModel = PaymentListModel.fromJson(json.decode(str));
class PaymentListModel {
PaymentListModel({
this.status,
this.data,
this.message,
});
String status;
List<Datum> data;
String message;
factory PaymentListModel.fromJson(Map<String, dynamic> json) => PaymentListModel(
status: json["status"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
message: json["message"],
);
Map<String, dynamic> toJson() => {
"status": status,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"message": message,
};
}
class Datum {
Datum({
this.idCategory,
this.categorySlug,
this.categoryName,
this.dataPayment,
});
int idCategory;
String categorySlug;
String categoryName;
List<DataPayment> dataPayment;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
idCategory: json["id_category"],
categorySlug: json["category_slug"],
categoryName: json["category_name"],
dataPayment: List<DataPayment>.from(json["data_payment"].map((x) => DataPayment.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id_category": idCategory,
"category_slug": categorySlug,
"category_name": categoryName,
"data_payment": List<dynamic>.from(dataPayment.map((x) => x.toJson())),
};
}
class DataPayment {
DataPayment({
this.paymentSlug,
this.paymentName,
this.paymentLogo,
});
String paymentSlug;
String paymentName;
String paymentLogo;
factory DataPayment.fromJson(Map<String, dynamic> json) => DataPayment(
paymentSlug: json["payment_slug"],
paymentName: json["payment_name"],
paymentLogo: json["payment_logo"],
);
Map<String, dynamic> toJson() => {
"payment_slug": paymentSlug,
"payment_name": paymentName,
"payment_logo": paymentLogo,
};
}

Flutter converting custom stacked objects to json

So I have a relatively complex object structure and I want to save it in SQFLite. But since this object has list of other objects, I thought that I would convert the list of subobjects to json and save this as text.
Like this:
"name": "String",
"Body": {
"Object1": [
{
"index": int,
}
],
"Object2": [
{
"index":2,
}
]
}
When I press a button a new object is created and added to the database. (rawInsert)
But this problem arises:
Unhandled Exception: DatabaseException(java.lang.String cannot be cast to java.lang.Integer)
Which as far as I understand it means that there was an error converting a string to an int.
The full error code
E/flutter (20088): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: DatabaseException(java.lang.String cannot be cast to java.lang.Integer) sql 'INSERT Into workoutPlan (name,id,workoutDays,pastId,timesDone,workoutBody) VALUES (?,?,?,?,?,?)' args [nummero uno, 2, [Monday, Friday], 345, 45, {Pause: [{timeInMilSec: 900, index: 5}], exercise: [{goal: 2, weightGoal: [15, 15, 15], name: PushUp, timeGoal: 900, index: 1, repGoal: 3, setGoal: [infinity, 15, 3]}]}]}
My model class:
import 'dart:convert';
PlanModel planModelFromJson(String str) => PlanModel.fromJson(json.decode(str));
String planModelToJson(PlanModel data) => json.encode(data.toJson());
class PlanModel {
PlanModel({
this.name,
this.id,
this.workoutDays,
this.pastId,
this.timesDone,
this.workoutBody,
});
String name;
int id;
List<String> workoutDays;
int pastId;
int timesDone;
WorkoutBody workoutBody;
factory PlanModel.fromJson(Map<String, dynamic> json) => PlanModel(
name: json["name"],
id: json["id"],
workoutDays: List<String>.from(json["workoutDays"].map((x) => x)),
pastId: json["pastId"],
timesDone: json["timesDone"],
workoutBody: WorkoutBody.fromJson(json["workoutBody"]),
);
Map<String, dynamic> toJson() => {
"name": name,
"id": id,
"workoutDays": List<dynamic>.from(workoutDays.map((x) => x)),
"pastId": pastId,
"timesDone": timesDone,
"workoutBody": workoutBody.toJson(),
};
}
class WorkoutBody {
WorkoutBody({
this.exercise,
this.pause,
});
List<Exercise> exercise;
List<Pause> pause;
factory WorkoutBody.fromJson(Map<String, dynamic> json) => WorkoutBody(
exercise: List<Exercise>.from(json["exercise"].map((x) => Exercise.fromJson(x))),
pause: List<Pause>.from(json["Pause"].map((x) => Pause.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"exercise": List<dynamic>.from(exercise.map((x) => x.toJson())),
"Pause": List<dynamic>.from(pause.map((x) => x.toJson())),
};
}
class Exercise {
Exercise({
this.index,
this.name,
this.goal,
this.repGoal,
this.weightGoal,
this.timeGoal,
this.setGoal,
});
int index;
String name;
int goal;
int repGoal;
List<int> weightGoal;
int timeGoal;
List<String> setGoal;
factory Exercise.fromJson(Map<String, dynamic> json) => Exercise(
index: json["index"],
name: json["name"],
goal: json["goal"],
repGoal: json["repGoal"],
weightGoal: List<int>.from(json["weightGoal"].map((x) => x)),
timeGoal: json["timeGoal"],
setGoal: List<String>.from(json["setGoal"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"index": index,
"name": name,
"goal": goal,
"repGoal": repGoal,
"weightGoal": List<dynamic>.from(weightGoal.map((x) => x)),
"timeGoal": timeGoal,
"setGoal": List<dynamic>.from(setGoal.map((x) => x)),
};
}
class Pause {
Pause({
this.index,
this.timeInMilSec,
});
int index;
int timeInMilSec;
factory Pause.fromJson(Map<String, dynamic> json) => Pause(
index: json["index"],
timeInMilSec: json["timeInMilSec"],
);
Map<String, dynamic> toJson() => {
"index": index,
"timeInMilSec": timeInMilSec,
};
}
I found the problem :)
In the planModel toJson() I had
"workoutDays": List<dynamic>.from(workoutDays.map((x) => x)),
and changed it to jsonDecode(workoutDays) and to read it again I used jsonEncode(src)
Flutter is probably getting your variable as a String.
To avoid any type problem I always do something like this:
int.tryParse(workoutBody.toString());
You should probably do this for all the stored data, especially when it comes to convert SQL query to dart int then json int.

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"])

Flutter/Dart Error - NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'map' with matching arguments

I'm receiving an Error following the Json Deserialisation cookbook
NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'map' with matching arguments.
Bundle Class
class Bundle {
String resourceType;
String id;
String type;
int total;
List<Link> link;
List<Entry> entry;
Bundle(
{this.resourceType,
this.id,
this.type,
this.total,
this.link,
this.entry});
factory Bundle.fromJson(Map<String, dynamic> json) {
return Bundle(
resourceType : json['resourceType'],
id : json['id'],
type : json['type'],
total : json['total'],
);
}
Code:
try {
await parsePerson(resultString);
} catch (e) {
print('Bundlelist Error: $e');
}
Future<List<Bundle>> parsePerson(String body) async {
List<Bundle> bundleList = [];
try {
final parsed = json.decode(body);
bundleList = parsed.map<Bundle>((json) => Bundle.fromJson(json)).toList;
} catch (e) {
print('FutureError: $e');
}
return bundleList;
}
My Result string (partial): Full json is here.
{"resourceType":"Bundle","id":"f26779b4-5c3c-4c52-83b4-c689516a6a08","type":"searchset","link":[{"relation":"self","url":"https://fhir-open.sandboxcerner.com/dstu2/0b8a0111-e8e6-4c26-a91c-5069cbc6b1ca/Patient?name=b\u0026_count=20"},{"relation":"next","url":"https://fhir-open.sandboxcerner.com/dstu2/0b8a0111-e8e6-4c26-a91c-5069cbc6b1ca/Patient?-pageContext=7018d2bc-6be4-48e1-b8a4-a40f4e98c98c\u0026-pageDirection=NEXT"}],"entry":[{"fullUrl":"https://fhir-open.sandboxcerner.com/dstu2/0b8a0111-e8e6-4c26-a91c-5069cbc6b1ca/Patient/6160015","resource":{"resourceType":"Patient","id":"6160015","meta":{"versionId":"0","lastUpdated":"2019-07-08T20:37:03.000Z"},"text":{"status":"generated","div":"\u003Cdiv\u003E\u003Cp\u003E\u003Cb\u003EPatient\u003C/b\u003E\u003C/p\u003E\u003Cp\u003E\u003Cb\u003EName\u003C/b\u003E: 111d3fcaffb244b2b207c07ffa5a14, bf607a7f1f284e8aa3559d52249bc7\u003C/p\u003E\u003Cp\u003E\u003Cb\u003EDOB\u003C/b\u003E: Mar 15, 1936\u003C/p\u003E\u003Cp\u003E\u003Cb\u003EAdministrative Gend
I've tried various suggestions from here including:
final parsed = jsonDecode(body).cast<Map<String, dynamic>>();
Returns
NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.
I'm quite lost as to what to try next.
You need an array, but your response is a map
You json string is too long, I can not paste full code contains your full json
You can copy paste , replace yourjsonstring and run full code below
Your json string contains control character \n and need to replace before parse
You can get all related class in full code
code snippet
String jsonString = '''yourjsonstring''';
String replaced = jsonString.replaceAll('\n',r'\\n');
final payload = payloadFromJson(replaced);
print(payload.link[0].relation);
print(payload.link[0].url);
print(payload.entry[0].resource.address[0].text);
full code
import 'package:flutter/material.dart';
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
String resourceType;
String id;
String type;
List<Link> link;
List<Entry> entry;
Payload({
this.resourceType,
this.id,
this.type,
this.link,
this.entry,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
resourceType: json["resourceType"],
id: json["id"],
type: json["type"],
link: List<Link>.from(json["link"].map((x) => Link.fromJson(x))),
entry: List<Entry>.from(json["entry"].map((x) => Entry.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"resourceType": resourceType,
"id": id,
"type": type,
"link": List<dynamic>.from(link.map((x) => x.toJson())),
"entry": List<dynamic>.from(entry.map((x) => x.toJson())),
};
}
class Entry {
String fullUrl;
Resource resource;
Entry({
this.fullUrl,
this.resource,
});
factory Entry.fromJson(Map<String, dynamic> json) => Entry(
fullUrl: json["fullUrl"],
resource: Resource.fromJson(json["resource"]),
);
Map<String, dynamic> toJson() => {
"fullUrl": fullUrl,
"resource": resource.toJson(),
};
}
class Resource {
ResourceType resourceType;
String id;
Meta meta;
TextClass text;
List<Identifier> identifier;
bool active;
List<Name> name;
List<Telecom> telecom;
Gender gender;
DateTime birthDate;
List<Address> address;
Resource({
this.resourceType,
this.id,
this.meta,
this.text,
this.identifier,
this.active,
this.name,
this.telecom,
this.gender,
this.birthDate,
this.address,
});
factory Resource.fromJson(Map<String, dynamic> json) => Resource(
resourceType: resourceTypeValues.map[json["resourceType"]],
id: json["id"],
meta: Meta.fromJson(json["meta"]),
text: TextClass.fromJson(json["text"]),
identifier: List<Identifier>.from(json["identifier"].map((x) => Identifier.fromJson(x))),
active: json["active"],
name: List<Name>.from(json["name"].map((x) => Name.fromJson(x))),
telecom: List<Telecom>.from(json["telecom"].map((x) => Telecom.fromJson(x))),
gender: genderValues.map[json["gender"]],
birthDate: DateTime.parse(json["birthDate"]),
address: List<Address>.from(json["address"].map((x) => Address.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"resourceType": resourceTypeValues.reverse[resourceType],
"id": id,
"meta": meta.toJson(),
"text": text.toJson(),
"identifier": List<dynamic>.from(identifier.map((x) => x.toJson())),
"active": active,
"name": List<dynamic>.from(name.map((x) => x.toJson())),
"telecom": List<dynamic>.from(telecom.map((x) => x.toJson())),
"gender": genderValues.reverse[gender],
"birthDate": "${birthDate.year.toString().padLeft(4, '0')}-${birthDate.month.toString().padLeft(2, '0')}-${birthDate.day.toString().padLeft(2, '0')}",
"address": List<dynamic>.from(address.map((x) => x.toJson())),
};
}
class Address {
AddressUse use;
String text;
List<String> line;
String city;
String state;
String postalCode;
String country;
AddressPeriod period;
Address({
this.use,
this.text,
this.line,
this.city,
this.state,
this.postalCode,
this.country,
this.period,
});
factory Address.fromJson(Map<String, dynamic> json) => Address(
use: addressUseValues.map[json["use"]],
text: json["text"],
line: List<String>.from(json["line"].map((x) => x)),
city: json["city"],
state: json["state"],
postalCode: json["postalCode"],
country: json["country"],
period: json["period"] == null ? null : AddressPeriod.fromJson(json["period"]),
);
Map<String, dynamic> toJson() => {
"use": addressUseValues.reverse[use],
"text": text,
"line": List<dynamic>.from(line.map((x) => x)),
"city": city,
"state": state,
"postalCode": postalCode,
"country": country,
"period": period == null ? null : period.toJson(),
};
}
class AddressPeriod {
DateTime start;
AddressPeriod({
this.start,
});
factory AddressPeriod.fromJson(Map<String, dynamic> json) => AddressPeriod(
start: DateTime.parse(json["start"]),
);
Map<String, dynamic> toJson() => {
"start": start.toIso8601String(),
};
}
enum AddressUse { HOME, WORK, MOBILE }
final addressUseValues = EnumValues({
"home": AddressUse.HOME,
"mobile": AddressUse.MOBILE,
"work": AddressUse.WORK
});
enum Gender { UNKNOWN, OTHER }
final genderValues = EnumValues({
"other": Gender.OTHER,
"unknown": Gender.UNKNOWN
});
class Identifier {
IdentifierUse use;
Type type;
IdentifierSystem system;
String identifierValue;
Value value;
AddressPeriod period;
Identifier({
this.use,
this.type,
this.system,
this.identifierValue,
this.value,
this.period,
});
factory Identifier.fromJson(Map<String, dynamic> json) => Identifier(
use: identifierUseValues.map[json["use"]],
type: Type.fromJson(json["type"]),
system: identifierSystemValues.map[json["system"]],
identifierValue: json["value"],
value: Value.fromJson(json["_value"]),
period: AddressPeriod.fromJson(json["period"]),
);
Map<String, dynamic> toJson() => {
"use": identifierUseValues.reverse[use],
"type": type.toJson(),
"system": identifierSystemValues.reverse[system],
"value": identifierValue,
"_value": value.toJson(),
"period": period.toJson(),
};
}
enum IdentifierSystem { URN_OID_2168401113883378700, URN_OID_111111, URN_OID_21684011138833421000110000112 }
final identifierSystemValues = EnumValues({
"urn:oid:1.1.1.1.1.1": IdentifierSystem.URN_OID_111111,
"urn:oid:2.16.840.1.113883.3.42.10001.100001.12": IdentifierSystem.URN_OID_21684011138833421000110000112,
"urn:oid:2.16.840.1.113883.3.787.0.0": IdentifierSystem.URN_OID_2168401113883378700
});
class Type {
List<Coding> coding;
TextEnum text;
Type({
this.coding,
this.text,
});
factory Type.fromJson(Map<String, dynamic> json) => Type(
coding: json["coding"] == null ? null : List<Coding>.from(json["coding"].map((x) => Coding.fromJson(x))),
text: textEnumValues.map[json["text"]],
);
Map<String, dynamic> toJson() => {
"coding": coding == null ? null : List<dynamic>.from(coding.map((x) => x.toJson())),
"text": textEnumValues.reverse[text],
};
}
class Coding {
String system;
Code code;
Display display;
bool userSelected;
Coding({
this.system,
this.code,
this.display,
this.userSelected,
});
factory Coding.fromJson(Map<String, dynamic> json) => Coding(
system: json["system"],
code: codeValues.map[json["code"]],
display: displayValues.map[json["display"]],
userSelected: json["userSelected"],
);
Map<String, dynamic> toJson() => {
"system": system,
"code": codeValues.reverse[code],
"display": displayValues.reverse[display],
"userSelected": userSelected,
};
}
enum Code { MR }
final codeValues = EnumValues({
"MR": Code.MR
});
enum Display { MEDICAL_RECORD_NUMBER }
final displayValues = EnumValues({
"Medical record number": Display.MEDICAL_RECORD_NUMBER
});
enum TextEnum { COMMUNITY_MEDICAL_RECORD_NUMBER, MRN, MILITARY_ID }
final textEnumValues = EnumValues({
"Community Medical Record Number": TextEnum.COMMUNITY_MEDICAL_RECORD_NUMBER,
"Military Id": TextEnum.MILITARY_ID,
"MRN": TextEnum.MRN
});
enum IdentifierUse { USUAL }
final identifierUseValues = EnumValues({
"usual": IdentifierUse.USUAL
});
class Value {
List<Extension> extension;
Value({
this.extension,
});
factory Value.fromJson(Map<String, dynamic> json) => Value(
extension: List<Extension>.from(json["extension"].map((x) => Extension.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"extension": List<dynamic>.from(extension.map((x) => x.toJson())),
};
}
class Extension {
String url;
String valueString;
Extension({
this.url,
this.valueString,
});
factory Extension.fromJson(Map<String, dynamic> json) => Extension(
url: json["url"],
valueString: json["valueString"],
);
Map<String, dynamic> toJson() => {
"url": url,
"valueString": valueString,
};
}
class Meta {
String versionId;
DateTime lastUpdated;
Meta({
this.versionId,
this.lastUpdated,
});
factory Meta.fromJson(Map<String, dynamic> json) => Meta(
versionId: json["versionId"],
lastUpdated: DateTime.parse(json["lastUpdated"]),
);
Map<String, dynamic> toJson() => {
"versionId": versionId,
"lastUpdated": lastUpdated.toIso8601String(),
};
}
class Name {
NameUse use;
String text;
List<String> family;
List<String> given;
List<String> prefix;
NamePeriod period;
List<String> suffix;
Name({
this.use,
this.text,
this.family,
this.given,
this.prefix,
this.period,
this.suffix,
});
factory Name.fromJson(Map<String, dynamic> json) => Name(
use: nameUseValues.map[json["use"]],
text: json["text"],
family: List<String>.from(json["family"].map((x) => x)),
given: List<String>.from(json["given"].map((x) => x)),
prefix: json["prefix"] == null ? null : List<String>.from(json["prefix"].map((x) => x)),
period: json["period"] == null ? null : NamePeriod.fromJson(json["period"]),
suffix: json["suffix"] == null ? null : List<String>.from(json["suffix"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"use": nameUseValues.reverse[use],
"text": text,
"family": List<dynamic>.from(family.map((x) => x)),
"given": List<dynamic>.from(given.map((x) => x)),
"prefix": prefix == null ? null : List<dynamic>.from(prefix.map((x) => x)),
"period": period == null ? null : period.toJson(),
"suffix": suffix == null ? null : List<dynamic>.from(suffix.map((x) => x)),
};
}
class NamePeriod {
DateTime start;
DateTime end;
NamePeriod({
this.start,
this.end,
});
factory NamePeriod.fromJson(Map<String, dynamic> json) => NamePeriod(
start: json["start"] == null ? null : DateTime.parse(json["start"]),
end: json["end"] == null ? null : DateTime.parse(json["end"]),
);
Map<String, dynamic> toJson() => {
"start": start == null ? null : start.toIso8601String(),
"end": end == null ? null : end.toIso8601String(),
};
}
enum NameUse { OFFICIAL, OLD }
final nameUseValues = EnumValues({
"official": NameUse.OFFICIAL,
"old": NameUse.OLD
});
enum ResourceType { PATIENT }
final resourceTypeValues = EnumValues({
"Patient": ResourceType.PATIENT
});
class Telecom {
TelecomSystem system;
ValueEnum value;
AddressUse use;
AddressPeriod period;
Telecom({
this.system,
this.value,
this.use,
this.period,
});
factory Telecom.fromJson(Map<String, dynamic> json) => Telecom(
system: telecomSystemValues.map[json["system"]],
value: valueEnumValues.map[json["value"]],
use: addressUseValues.map[json["use"]],
period: json["period"] == null ? null : AddressPeriod.fromJson(json["period"]),
);
Map<String, dynamic> toJson() => {
"system": telecomSystemValues.reverse[system],
"value": valueEnumValues.reverse[value],
"use": addressUseValues.reverse[use],
"period": period == null ? null : period.toJson(),
};
}
enum TelecomSystem { PHONE, EMAIL }
final telecomSystemValues = EnumValues({
"email": TelecomSystem.EMAIL,
"phone": TelecomSystem.PHONE
});
enum ValueEnum { THE_3213213213, NAME_FAKEMAIL_COM, THE_8888888888 }
final valueEnumValues = EnumValues({
"name#fakemail.com": ValueEnum.NAME_FAKEMAIL_COM,
"321-321-3213": ValueEnum.THE_3213213213,
"888-888-8888": ValueEnum.THE_8888888888
});
class TextClass {
Status status;
String div;
TextClass({
this.status,
this.div,
});
factory TextClass.fromJson(Map<String, dynamic> json) => TextClass(
status: statusValues.map[json["status"]],
div: json["div"],
);
Map<String, dynamic> toJson() => {
"status": statusValues.reverse[status],
"div": div,
};
}
enum Status { GENERATED }
final statusValues = EnumValues({
"generated": Status.GENERATED
});
class Link {
String relation;
String url;
Link({
this.relation,
this.url,
});
factory Link.fromJson(Map<String, dynamic> json) => Link(
relation: json["relation"],
url: json["url"],
);
Map<String, dynamic> toJson() => {
"relation": relation,
"url": url,
};
}
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
String jsonString = '''yourjsonstring''';
//String jsonString = '''{"newLine": "here is a \n newline \u003E \u0026 \u003C aaa"}''';
void _incrementCounter() {
String replaced = jsonString.replaceAll('\n',r'\\n');
final payload = payloadFromJson(replaced);
print(payload.link[0].relation);
print(payload.link[0].url);
print(payload.entry[0].resource.address[0].text);
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}