the JSON data in question is https://api.aladhan.com/v1/calendarByCity?city=London&country=United%20Kingdom&method=8&month=06&year=2021
List <PrayerTimesPerDay> prayerList; // Read the contents of nested List
// the bottom section is pretty inaccurate afaik
factory PrayerTimesPerDay.fromJson(Map<String, dynamic> json) {
List timings = json["data"];
return PrayerTimesPerDay(
day: json['gregorian']['weekday']['en'],
fajr: json['Fajr'],
zuhr: json['Dhuhr'],
asr: json['Asr'],
maghrib: json['Maghrib'],
isha: json['sha'],
);
}
So my intention is to read the timings and the day into a class called PrayerTimesPerDay which had the following variables
final String day;
final String fajr;
final String zuhr;
final String asr;
final String maghrib;
final String isha;
my concern is, I dont really understand how be able to convert such a kind of data into these variables, I manage to extract them as List in my async function and able to print somedata from it, and even planned in making a for loop(which didnt workout) that adds them into a list.
would be appreciated if there was an explaination
SalamoAlikom brother. Here's how I will go about it.
factory PrayerTimesPerDay.fromJson(Map<String, dynamic> json) {
var data = json["data"];
var data_00 = data[0]; //<-- you could loop over here to get all the data!!!
return PrayerTimesPerDay(
day: data_00['date']['gregorian']['weekday']['en'],
fajr: data_00[timings]['Fajr'],
zuhr: data_00[timings]['Dhuhr'],
asr: data_00[timings]['Asr'],
maghrib: data_00[timings]['Maghrib'],
isha: data_00[timings]['sha'],
);
}
this might work however I would strongly recommend code generation as mentioned in the official documentation. That will require you to architect your objects so that they can be easily converted from JSON to play dart object.
You can covert your response here
class PrayerTime {
int code;
String status;
List<Data> data;
PrayerTime({this.code, this.status, this.data});
PrayerTime.fromJson(Map<String, dynamic> json) {
code = json['code'];
status = json['status'];
if (json['data'] != null) {
data = new List<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['code'] = this.code;
data['status'] = this.status;
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
Timings timings;
Date date;
Meta meta;
Data({this.timings, this.date, this.meta});
Data.fromJson(Map<String, dynamic> json) {
timings =
json['timings'] != null ? new Timings.fromJson(json['timings']) : null;
date = json['date'] != null ? new Date.fromJson(json['date']) : null;
meta = json['meta'] != null ? new Meta.fromJson(json['meta']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.timings != null) {
data['timings'] = this.timings.toJson();
}
if (this.date != null) {
data['date'] = this.date.toJson();
}
if (this.meta != null) {
data['meta'] = this.meta.toJson();
}
return data;
}
}
class Timings {
String fajr;
String sunrise;
String dhuhr;
String asr;
String sunset;
String maghrib;
String isha;
String imsak;
String midnight;
Timings(
{this.fajr,
this.sunrise,
this.dhuhr,
this.asr,
this.sunset,
this.maghrib,
this.isha,
this.imsak,
this.midnight});
Timings.fromJson(Map<String, dynamic> json) {
fajr = json['Fajr'];
sunrise = json['Sunrise'];
dhuhr = json['Dhuhr'];
asr = json['Asr'];
sunset = json['Sunset'];
maghrib = json['Maghrib'];
isha = json['Isha'];
imsak = json['Imsak'];
midnight = json['Midnight'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['Fajr'] = this.fajr;
data['Sunrise'] = this.sunrise;
data['Dhuhr'] = this.dhuhr;
data['Asr'] = this.asr;
data['Sunset'] = this.sunset;
data['Maghrib'] = this.maghrib;
data['Isha'] = this.isha;
data['Imsak'] = this.imsak;
data['Midnight'] = this.midnight;
return data;
}
}
class Date {
String readable;
String timestamp;
Gregorian gregorian;
Hijri hijri;
Date({this.readable, this.timestamp, this.gregorian, this.hijri});
Date.fromJson(Map<String, dynamic> json) {
readable = json['readable'];
timestamp = json['timestamp'];
gregorian = json['gregorian'] != null
? new Gregorian.fromJson(json['gregorian'])
: null;
hijri = json['hijri'] != null ? new Hijri.fromJson(json['hijri']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['readable'] = this.readable;
data['timestamp'] = this.timestamp;
if (this.gregorian != null) {
data['gregorian'] = this.gregorian.toJson();
}
if (this.hijri != null) {
data['hijri'] = this.hijri.toJson();
}
return data;
}
}
class Gregorian {
String date;
String format;
String day;
Weekday weekday;
Month month;
String year;
Designation designation;
Gregorian(
{this.date,
this.format,
this.day,
this.weekday,
this.month,
this.year,
this.designation});
Gregorian.fromJson(Map<String, dynamic> json) {
date = json['date'];
format = json['format'];
day = json['day'];
weekday =
json['weekday'] != null ? new Weekday.fromJson(json['weekday']) : null;
month = json['month'] != null ? new Month.fromJson(json['month']) : null;
year = json['year'];
designation = json['designation'] != null
? new Designation.fromJson(json['designation'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['date'] = this.date;
data['format'] = this.format;
data['day'] = this.day;
if (this.weekday != null) {
data['weekday'] = this.weekday.toJson();
}
if (this.month != null) {
data['month'] = this.month.toJson();
}
data['year'] = this.year;
if (this.designation != null) {
data['designation'] = this.designation.toJson();
}
return data;
}
}
class Weekday {
String en;
Weekday({this.en});
Weekday.fromJson(Map<String, dynamic> json) {
en = json['en'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['en'] = this.en;
return data;
}
}
class Month {
int number;
String en;
Month({this.number, this.en});
Month.fromJson(Map<String, dynamic> json) {
number = json['number'];
en = json['en'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['number'] = this.number;
data['en'] = this.en;
return data;
}
}
class Designation {
String abbreviated;
String expanded;
Designation({this.abbreviated, this.expanded});
Designation.fromJson(Map<String, dynamic> json) {
abbreviated = json['abbreviated'];
expanded = json['expanded'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['abbreviated'] = this.abbreviated;
data['expanded'] = this.expanded;
return data;
}
}
class Hijri {
String date;
String format;
String day;
Weekday weekday;
Month month;
String year;
Designation designation;
List<Null> holidays;
Hijri(
{this.date,
this.format,
this.day,
this.weekday,
this.month,
this.year,
this.designation,
this.holidays});
Hijri.fromJson(Map<String, dynamic> json) {
date = json['date'];
format = json['format'];
day = json['day'];
weekday =
json['weekday'] != null ? new Weekday.fromJson(json['weekday']) : null;
month = json['month'] != null ? new Month.fromJson(json['month']) : null;
year = json['year'];
designation = json['designation'] != null
? new Designation.fromJson(json['designation'])
: null;
if (json['holidays'] != null) {
holidays = new List<Null>();
json['holidays'].forEach((v) {
holidays.add(new Null.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['date'] = this.date;
data['format'] = this.format;
data['day'] = this.day;
if (this.weekday != null) {
data['weekday'] = this.weekday.toJson();
}
if (this.month != null) {
data['month'] = this.month.toJson();
}
data['year'] = this.year;
if (this.designation != null) {
data['designation'] = this.designation.toJson();
}
if (this.holidays != null) {
data['holidays'] = this.holidays.map((v) => v.toJson()).toList();
}
return data;
}
}
class Weekday {
String en;
String ar;
Weekday({this.en, this.ar});
Weekday.fromJson(Map<String, dynamic> json) {
en = json['en'];
ar = json['ar'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['en'] = this.en;
data['ar'] = this.ar;
return data;
}
}
class Month {
int number;
String en;
String ar;
Month({this.number, this.en, this.ar});
Month.fromJson(Map<String, dynamic> json) {
number = json['number'];
en = json['en'];
ar = json['ar'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['number'] = this.number;
data['en'] = this.en;
data['ar'] = this.ar;
return data;
}
}
class Meta {
double latitude;
double longitude;
String timezone;
Method method;
String latitudeAdjustmentMethod;
String midnightMode;
String school;
Offset offset;
Meta(
{this.latitude,
this.longitude,
this.timezone,
this.method,
this.latitudeAdjustmentMethod,
this.midnightMode,
this.school,
this.offset});
Meta.fromJson(Map<String, dynamic> json) {
latitude = json['latitude'];
longitude = json['longitude'];
timezone = json['timezone'];
method =
json['method'] != null ? new Method.fromJson(json['method']) : null;
latitudeAdjustmentMethod = json['latitudeAdjustmentMethod'];
midnightMode = json['midnightMode'];
school = json['school'];
offset =
json['offset'] != null ? new Offset.fromJson(json['offset']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['latitude'] = this.latitude;
data['longitude'] = this.longitude;
data['timezone'] = this.timezone;
if (this.method != null) {
data['method'] = this.method.toJson();
}
data['latitudeAdjustmentMethod'] = this.latitudeAdjustmentMethod;
data['midnightMode'] = this.midnightMode;
data['school'] = this.school;
if (this.offset != null) {
data['offset'] = this.offset.toJson();
}
return data;
}
}
class Method {
int id;
String name;
Params params;
Method({this.id, this.name, this.params});
Method.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
params =
json['params'] != null ? new Params.fromJson(json['params']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
if (this.params != null) {
data['params'] = this.params.toJson();
}
return data;
}
}
class Params {
double fajr;
String isha;
Params({this.fajr, this.isha});
Params.fromJson(Map<String, dynamic> json) {
fajr = json['Fajr'];
isha = json['Isha'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['Fajr'] = this.fajr;
data['Isha'] = this.isha;
return data;
}
}
class Offset {
int imsak;
int fajr;
int sunrise;
int dhuhr;
int asr;
int maghrib;
int sunset;
int isha;
int midnight;
Offset(
{this.imsak,
this.fajr,
this.sunrise,
this.dhuhr,
this.asr,
this.maghrib,
this.sunset,
this.isha,
this.midnight});
Offset.fromJson(Map<String, dynamic> json) {
imsak = json['Imsak'];
fajr = json['Fajr'];
sunrise = json['Sunrise'];
dhuhr = json['Dhuhr'];
asr = json['Asr'];
maghrib = json['Maghrib'];
sunset = json['Sunset'];
isha = json['Isha'];
midnight = json['Midnight'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['Imsak'] = this.imsak;
data['Fajr'] = this.fajr;
data['Sunrise'] = this.sunrise;
data['Dhuhr'] = this.dhuhr;
data['Asr'] = this.asr;
data['Maghrib'] = this.maghrib;
data['Sunset'] = this.sunset;
data['Isha'] = this.isha;
data['Midnight'] = this.midnight;
return data;
}
}
Here is a full Model class you can read and understand. It took too much time but I appreciate your question.
You just copy the and save it in a separate file like model.dart:
// To parse this JSON data, do
//
// final welcome = welcomeFromMap(jsonString);
import 'dart:convert';
class Welcome {
Welcome({
this.code,
this.status,
this.data,
});
final int code;
final String status;
final List<Datum> data;
factory Welcome.fromJson(String str) => Welcome.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Welcome.fromMap(Map<String, dynamic> json) => Welcome(
code: json["code"] == null ? null : json["code"],
status: json["status"] == null ? null : json["status"],
data: json["data"] == null ? null : List<Datum>.from(json["data"].map((x) => Datum.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"code": code == null ? null : code,
"status": status == null ? null : status,
"data": data == null ? null : List<dynamic>.from(data.map((x) => x.toMap())),
};
}
class Datum {
Datum({
this.timings,
this.date,
this.meta,
});
final Timings timings;
final Date date;
final Meta meta;
factory Datum.fromJson(String str) => Datum.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Datum.fromMap(Map<String, dynamic> json) => Datum(
timings: json["timings"] == null ? null : Timings.fromMap(json["timings"]),
date: json["date"] == null ? null : Date.fromMap(json["date"]),
meta: json["meta"] == null ? null : Meta.fromMap(json["meta"]),
);
Map<String, dynamic> toMap() => {
"timings": timings == null ? null : timings.toMap(),
"date": date == null ? null : date.toMap(),
"meta": meta == null ? null : meta.toMap(),
};
}
class Date {
Date({
this.readable,
this.timestamp,
this.gregorian,
this.hijri,
});
final String readable;
final String timestamp;
final Gregorian gregorian;
final Hijri hijri;
factory Date.fromJson(String str) => Date.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Date.fromMap(Map<String, dynamic> json) => Date(
readable: json["readable"] == null ? null : json["readable"],
timestamp: json["timestamp"] == null ? null : json["timestamp"],
gregorian: json["gregorian"] == null ? null : Gregorian.fromMap(json["gregorian"]),
hijri: json["hijri"] == null ? null : Hijri.fromMap(json["hijri"]),
);
Map<String, dynamic> toMap() => {
"readable": readable == null ? null : readable,
"timestamp": timestamp == null ? null : timestamp,
"gregorian": gregorian == null ? null : gregorian.toMap(),
"hijri": hijri == null ? null : hijri.toMap(),
};
}
class Gregorian {
Gregorian({
this.date,
this.format,
this.day,
this.weekday,
this.month,
this.year,
this.designation,
});
final String date;
final Format format;
final String day;
final GregorianWeekday weekday;
final GregorianMonth month;
final String year;
final Designation designation;
factory Gregorian.fromJson(String str) => Gregorian.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Gregorian.fromMap(Map<String, dynamic> json) => Gregorian(
date: json["date"] == null ? null : json["date"],
format: json["format"] == null ? null : formatValues.map[json["format"]],
day: json["day"] == null ? null : json["day"],
weekday: json["weekday"] == null ? null : GregorianWeekday.fromMap(json["weekday"]),
month: json["month"] == null ? null : GregorianMonth.fromMap(json["month"]),
year: json["year"] == null ? null : json["year"],
designation: json["designation"] == null ? null : Designation.fromMap(json["designation"]),
);
Map<String, dynamic> toMap() => {
"date": date == null ? null : date,
"format": format == null ? null : formatValues.reverse[format],
"day": day == null ? null : day,
"weekday": weekday == null ? null : weekday.toMap(),
"month": month == null ? null : month.toMap(),
"year": year == null ? null : year,
"designation": designation == null ? null : designation.toMap(),
};
}
class Designation {
Designation({
this.abbreviated,
this.expanded,
});
final Abbreviated abbreviated;
final Expanded expanded;
factory Designation.fromJson(String str) => Designation.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Designation.fromMap(Map<String, dynamic> json) => Designation(
abbreviated: json["abbreviated"] == null ? null : abbreviatedValues.map[json["abbreviated"]],
expanded: json["expanded"] == null ? null : expandedValues.map[json["expanded"]],
);
Map<String, dynamic> toMap() => {
"abbreviated": abbreviated == null ? null : abbreviatedValues.reverse[abbreviated],
"expanded": expanded == null ? null : expandedValues.reverse[expanded],
};
}
enum Abbreviated { AD, AH }
final abbreviatedValues = EnumValues({
"AD": Abbreviated.AD,
"AH": Abbreviated.AH
});
enum Expanded { ANNO_DOMINI, ANNO_HEGIRAE }
final expandedValues = EnumValues({
"Anno Domini": Expanded.ANNO_DOMINI,
"Anno Hegirae": Expanded.ANNO_HEGIRAE
});
enum Format { DD_MM_YYYY }
final formatValues = EnumValues({
"DD-MM-YYYY": Format.DD_MM_YYYY
});
class GregorianMonth {
GregorianMonth({
this.number,
this.en,
});
final int number;
final PurpleEn en;
factory GregorianMonth.fromJson(String str) => GregorianMonth.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory GregorianMonth.fromMap(Map<String, dynamic> json) => GregorianMonth(
number: json["number"] == null ? null : json["number"],
en: json["en"] == null ? null : purpleEnValues.map[json["en"]],
);
Map<String, dynamic> toMap() => {
"number": number == null ? null : number,
"en": en == null ? null : purpleEnValues.reverse[en],
};
}
enum PurpleEn { JUNE }
final purpleEnValues = EnumValues({
"June": PurpleEn.JUNE
});
class GregorianWeekday {
GregorianWeekday({
this.en,
});
final String en;
factory GregorianWeekday.fromJson(String str) => GregorianWeekday.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory GregorianWeekday.fromMap(Map<String, dynamic> json) => GregorianWeekday(
en: json["en"] == null ? null : json["en"],
);
Map<String, dynamic> toMap() => {
"en": en == null ? null : en,
};
}
class Hijri {
Hijri({
this.date,
this.format,
this.day,
this.weekday,
this.month,
this.year,
this.designation,
this.holidays,
});
final String date;
final Format format;
final String day;
final HijriWeekday weekday;
final HijriMonth month;
final String year;
final Designation designation;
final List<dynamic> holidays;
factory Hijri.fromJson(String str) => Hijri.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Hijri.fromMap(Map<String, dynamic> json) => Hijri(
date: json["date"] == null ? null : json["date"],
format: json["format"] == null ? null : formatValues.map[json["format"]],
day: json["day"] == null ? null : json["day"],
weekday: json["weekday"] == null ? null : HijriWeekday.fromMap(json["weekday"]),
month: json["month"] == null ? null : HijriMonth.fromMap(json["month"]),
year: json["year"] == null ? null : json["year"],
designation: json["designation"] == null ? null : Designation.fromMap(json["designation"]),
holidays: json["holidays"] == null ? null : List<dynamic>.from(json["holidays"].map((x) => x)),
);
Map<String, dynamic> toMap() => {
"date": date == null ? null : date,
"format": format == null ? null : formatValues.reverse[format],
"day": day == null ? null : day,
"weekday": weekday == null ? null : weekday.toMap(),
"month": month == null ? null : month.toMap(),
"year": year == null ? null : year,
"designation": designation == null ? null : designation.toMap(),
"holidays": holidays == null ? null : List<dynamic>.from(holidays.map((x) => x)),
};
}
class HijriMonth {
HijriMonth({
this.number,
this.en,
this.ar,
});
final int number;
final FluffyEn en;
final Ar ar;
factory HijriMonth.fromJson(String str) => HijriMonth.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory HijriMonth.fromMap(Map<String, dynamic> json) => HijriMonth(
number: json["number"] == null ? null : json["number"],
en: json["en"] == null ? null : fluffyEnValues.map[json["en"]],
ar: json["ar"] == null ? null : arValues.map[json["ar"]],
);
Map<String, dynamic> toMap() => {
"number": number == null ? null : number,
"en": en == null ? null : fluffyEnValues.reverse[en],
"ar": ar == null ? null : arValues.reverse[ar],
};
}
enum Ar { EMPTY, AR }
final arValues = EnumValues({
"ذوالقعدة": Ar.AR,
"شَوّال": Ar.EMPTY
});
enum FluffyEn { SHAWWL, DH_AL_QA_DAH }
final fluffyEnValues = EnumValues({
"Dhū al-Qaʿdah": FluffyEn.DH_AL_QA_DAH,
"Shawwāl": FluffyEn.SHAWWL
});
class HijriWeekday {
HijriWeekday({
this.en,
this.ar,
});
final String en;
final String ar;
factory HijriWeekday.fromJson(String str) => HijriWeekday.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory HijriWeekday.fromMap(Map<String, dynamic> json) => HijriWeekday(
en: json["en"] == null ? null : json["en"],
ar: json["ar"] == null ? null : json["ar"],
);
Map<String, dynamic> toMap() => {
"en": en == null ? null : en,
"ar": ar == null ? null : ar,
};
}
class Meta {
Meta({
this.latitude,
this.longitude,
this.timezone,
this.method,
this.latitudeAdjustmentMethod,
this.midnightMode,
this.school,
this.offset,
});
final double latitude;
final double longitude;
final Timezone timezone;
final Method method;
final LatitudeAdjustmentMethod latitudeAdjustmentMethod;
final MidnightMode midnightMode;
final MidnightMode school;
final Map<String, int> offset;
factory Meta.fromJson(String str) => Meta.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Meta.fromMap(Map<String, dynamic> json) => Meta(
latitude: json["latitude"] == null ? null : json["latitude"].toDouble(),
longitude: json["longitude"] == null ? null : json["longitude"].toDouble(),
timezone: json["timezone"] == null ? null : timezoneValues.map[json["timezone"]],
method: json["method"] == null ? null : Method.fromMap(json["method"]),
latitudeAdjustmentMethod: json["latitudeAdjustmentMethod"] == null ? null : latitudeAdjustmentMethodValues.map[json["latitudeAdjustmentMethod"]],
midnightMode: json["midnightMode"] == null ? null : midnightModeValues.map[json["midnightMode"]],
school: json["school"] == null ? null : midnightModeValues.map[json["school"]],
offset: json["offset"] == null ? null : Map.from(json["offset"]).map((k, v) => MapEntry<String, int>(k, v)),
);
Map<String, dynamic> toMap() => {
"latitude": latitude == null ? null : latitude,
"longitude": longitude == null ? null : longitude,
"timezone": timezone == null ? null : timezoneValues.reverse[timezone],
"method": method == null ? null : method.toMap(),
"latitudeAdjustmentMethod": latitudeAdjustmentMethod == null ? null : latitudeAdjustmentMethodValues.reverse[latitudeAdjustmentMethod],
"midnightMode": midnightMode == null ? null : midnightModeValues.reverse[midnightMode],
"school": school == null ? null : midnightModeValues.reverse[school],
"offset": offset == null ? null : Map.from(offset).map((k, v) => MapEntry<String, dynamic>(k, v)),
};
}
enum LatitudeAdjustmentMethod { ANGLE_BASED }
final latitudeAdjustmentMethodValues = EnumValues({
"ANGLE_BASED": LatitudeAdjustmentMethod.ANGLE_BASED
});
class Method {
Method({
this.id,
this.name,
this.params,
});
final int id;
final Name name;
final Params params;
factory Method.fromJson(String str) => Method.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Method.fromMap(Map<String, dynamic> json) => Method(
id: json["id"] == null ? null : json["id"],
name: json["name"] == null ? null : nameValues.map[json["name"]],
params: json["params"] == null ? null : Params.fromMap(json["params"]),
);
Map<String, dynamic> toMap() => {
"id": id == null ? null : id,
"name": name == null ? null : nameValues.reverse[name],
"params": params == null ? null : params.toMap(),
};
}
enum Name { GULF_REGION }
final nameValues = EnumValues({
"Gulf Region": Name.GULF_REGION
});
class Params {
Params({
this.fajr,
this.isha,
});
final double fajr;
final Isha isha;
factory Params.fromJson(String str) => Params.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Params.fromMap(Map<String, dynamic> json) => Params(
fajr: json["Fajr"] == null ? null : json["Fajr"].toDouble(),
isha: json["Isha"] == null ? null : ishaValues.map[json["Isha"]],
);
Map<String, dynamic> toMap() => {
"Fajr": fajr == null ? null : fajr,
"Isha": isha == null ? null : ishaValues.reverse[isha],
};
}
enum Isha { THE_90_MIN }
final ishaValues = EnumValues({
"90 min": Isha.THE_90_MIN
});
enum MidnightMode { STANDARD }
final midnightModeValues = EnumValues({
"STANDARD": MidnightMode.STANDARD
});
enum Timezone { EUROPE_LONDON }
final timezoneValues = EnumValues({
"Europe/London": Timezone.EUROPE_LONDON
});
class Timings {
Timings({
this.fajr,
this.sunrise,
this.dhuhr,
this.asr,
this.sunset,
this.maghrib,
this.isha,
this.imsak,
this.midnight,
});
final Fajr fajr;
final String sunrise;
final String dhuhr;
final String asr;
final String sunset;
final String maghrib;
final String isha;
final Imsak imsak;
final String midnight;
factory Timings.fromJson(String str) => Timings.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Timings.fromMap(Map<String, dynamic> json) => Timings(
fajr: json["Fajr"] == null ? null : fajrValues.map[json["Fajr"]],
sunrise: json["Sunrise"] == null ? null : json["Sunrise"],
dhuhr: json["Dhuhr"] == null ? null : json["Dhuhr"],
asr: json["Asr"] == null ? null : json["Asr"],
sunset: json["Sunset"] == null ? null : json["Sunset"],
maghrib: json["Maghrib"] == null ? null : json["Maghrib"],
isha: json["Isha"] == null ? null : json["Isha"],
imsak: json["Imsak"] == null ? null : imsakValues.map[json["Imsak"]],
midnight: json["Midnight"] == null ? null : json["Midnight"],
);
Map<String, dynamic> toMap() => {
"Fajr": fajr == null ? null : fajrValues.reverse[fajr],
"Sunrise": sunrise == null ? null : sunrise,
"Dhuhr": dhuhr == null ? null : dhuhr,
"Asr": asr == null ? null : asr,
"Sunset": sunset == null ? null : sunset,
"Maghrib": maghrib == null ? null : maghrib,
"Isha": isha == null ? null : isha,
"Imsak": imsak == null ? null : imsakValues.reverse[imsak],
"Midnight": midnight == null ? null : midnight,
};
}
enum Fajr { THE_0219_BST, THE_0218_BST, THE_0220_BST, THE_0221_BST, THE_0222_BST }
final fajrValues = EnumValues({
"02:18 (BST)": Fajr.THE_0218_BST,
"02:19 (BST)": Fajr.THE_0219_BST,
"02:20 (BST)": Fajr.THE_0220_BST,
"02:21 (BST)": Fajr.THE_0221_BST,
"02:22 (BST)": Fajr.THE_0222_BST
});
enum Imsak { THE_0209_BST, THE_0208_BST, THE_0210_BST, THE_0211_BST, THE_0212_BST }
final imsakValues = EnumValues({
"02:08 (BST)": Imsak.THE_0208_BST,
"02:09 (BST)": Imsak.THE_0209_BST,
"02:10 (BST)": Imsak.THE_0210_BST,
"02:11 (BST)": Imsak.THE_0211_BST,
"02:12 (BST)": Imsak.THE_0212_BST
});
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;
}
}
You can use only those class which is required.
Related
Json list -
[
{
"date": "2022-10-10T09:53:40.835519+05:30",
"value": 10
},
{
"date": "2022-10-13T09:53:40.835519+05:30",
"value": 12
},
{
"date": "2022-10-13T10:53:40.835519+05:30",
"value": 15
},
{
"date": "2022-10-15T10:53:40.835519+05:30",
"value": 20
}
]
in above list if there are multiple dateTimes for same day ( ex. 2022-10-13 )
so how to mark 2022-10-13T10:53 date in object list as isLatestDateForSameDay=true as 2022-10-
13T10:53 is latest compare to 2022-10-13T09:53.
and if there is only one dateTime then it should also marked as isLatestDateForSameDay=true
ex. (2022-10-10T09:53:40.835519+05:30 and 2022-10-15T10:53:40.835519+05:30)
DataListItem class -
class DataListItem {
String date;
int value;
bool isLatestDate;
DataListItem({
required this.date,
required this.value,
this.isLatestDateForSameDay = false,
});
}
Expected list of Objects -
[
DataListItem(date: '2022-10-10T09:53:40.835519+05:30', value: 10, isLatestDateForSameDay: true),
DataListItem(date: '2022-10-13T09:53:40.835519+05:30', value: 12, isLatestDateForSameDay: false),
DataListItem(date: '2022-10-13T10:53:40.835519+05:30', value: 15, isLatestDateForSameDay: true),
DataListItem(date: '2022-10-15T10:53:40.835519+05:30', value: 20, isLatestDateForSameDay: true),
];
Lets assume your json is jsonData with collection package you can get what you want:
var grouped = groupBy(
jsonData,
(Map item) => (item['date'] as String).substring(0, 10),
);
List<DataListItem> result = [];
for (var element in grouped.entries) {
if (element.value.length == 1) {
result.add(DataListItem(
date: element.value.first['date'] as String,
value: element.value.first['value'] as int,
isLatestDate: true));
} else {
var latesItem = findLatestDate(element.value);
element.value.remove(latesItem);
result.add(DataListItem(
date: latesItem['date'] as String,
value: latesItem['value'] as int,
isLatestDate: true));
element.value.forEach((e) => result.add(DataListItem(
date: e['date'] as String,
value: e['value'] as int,
isLatestDate: false)));
}
}
Map<String, dynamic> findLatestDate(List<Map<String, dynamic>> dateList) {
Map<String, dynamic>? result;
for (var element in dateList) {
if (result == null) {
result = element;
} else {
DateTime resultDate =
DateFormat("yyyy-MM-ddThh:mm:ss").parse(result['date'] as String);
DateTime tempDate =
DateFormat("yyyy-MM-ddThh:mm:ss").parse(element['date'] as String);
if (tempDate.isAfter(resultDate)) {
result = element;
}
}
}
return result!;
}
for (var element in result) {
print("result= ${element.date} ${element.value} ${element.isLatestDate}");
// result= 2022-10-10T09:53:40.835519+05:30 10 true
// result= 2022-10-13T10:53:40.835519+05:30 15 true
// result= 2022-10-13T09:53:40.835519+05:30 12 false
// result= 2022-10-15T10:53:40.835519+05:30 20 true
}
also use intl for DateFormat.
Try sorting the list with DateTime.parse()
List<DataListItem> dataListItemlist = [];
list.sort(
(a, b) {
return DateTime.parse(a["date"]).compareTo(DateTime.parse(b["date"]));
},
);
List<String> repeatedDate = [];
for (var i = list.length - 1; i >= 0; i--) {
Map item = list[i];
DateTime date = DateTime.parse(item["date"]);
int day = date.day;
int month = date.month;
int year = date.year;
String formatedDate = "$day-$month-$year";
if (repeatedDate.contains(formatedDate)) {
dataListItemlist.add(
DataListItem(
date: item["date"],
value: item["value"],
isLatestDateForSameDay: false,
),
);
} else {
dataListItemlist.add(
DataListItem(
date: item["date"],
value: item["value"],
isLatestDateForSameDay: true,
),
);
repeatedDate.add(formatedDate);
}
}
I'm Trying to get a list of users from my api through ApiService and model it in my UserModel class.
It's giving me this error The argument type 'List<Result>?' can't be assigned to the parameter type 'List<Result>'.
The results are also not showing on the screen.
Much obliged
If the provided code is not enough and you want to take a look at the full project, here's the repo:
https://github.com/renslakens/SkoolWorkshopApp.git
UserModel class
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
import 'dart:convert';
class UserModel {
UserModel({
required this.status,
required this.result,
});
int status;
List<Result> result;
factory UserModel.fromJson(Map<String, dynamic> json) =>
UserModel(
status: json["status"] == null ? null : json["status"],
result: json["result"] == null ? null : List<Result>.from(
json["result"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() =>
{
"status": status == null ? null : status,
"result": result == null ? null : List<dynamic>.from(result.map((x) => x.toJson())),
};
}
class Result {
Result userModelFromJson(String str) => Result.fromJson(json.decode(str));
String userModelToJson(UserModel data) => json.encode(data.toJson());
Result({
required this.docentId,
required this.naam,
required this.achternaam,
required this.emailadres,
required this.geboortedatum,
required this.geboorteplaats,
this.maxRijafstand,
this.heeftRijbewijs,
this.heeftAuto,
required this.straat,
required this.huisnummer,
required this.geslacht,
required this.nationaliteit,
required this.woonplaats,
required this.postcode,
required this.land,
required this.wachtwoord,
required this.isAccepted,
this.isFlexwerker,
});
int docentId;
String naam;
String achternaam;
String emailadres;
String geboortedatum;
String geboorteplaats;
dynamic maxRijafstand;
dynamic heeftRijbewijs;
dynamic heeftAuto;
String straat;
int huisnummer;
String geslacht;
String nationaliteit;
String woonplaats;
String postcode;
String land;
String wachtwoord;
int isAccepted;
dynamic isFlexwerker;
factory Result.fromJson(Map<String, dynamic> json) =>
Result(
docentId: json["docentID"] == null ? null : json["docentID"],
naam: json["naam"] == null ? null : json["naam"],
achternaam: json["achternaam"] == null ? null : json["achternaam"],
emailadres: json["emailadres"] == null ? null : json["emailadres"],
geboortedatum: json["geboortedatum"] == null ? null : (json["geboortedatum"]),
geboorteplaats: json["geboorteplaats"] == null
? null
: json["geboorteplaats"],
maxRijafstand: json["maxRijafstand"],
heeftRijbewijs: json["heeftRijbewijs"],
heeftAuto: json["heeftAuto"],
straat: json["straat"] == null ? null : json["straat"],
huisnummer: json["huisnummer"] == null ? null : json["huisnummer"],
geslacht: json["geslacht"] == null ? null : json["geslacht"],
nationaliteit: json["nationaliteit"] == null
? null
: json["nationaliteit"],
woonplaats: json["woonplaats"] == null ? null : json["woonplaats"],
postcode: json["postcode"] == null ? null : json["postcode"],
land: json["land"] == null ? null : json["land"],
wachtwoord: json["wachtwoord"] == null ? null : json["wachtwoord"],
isAccepted: json["isAccepted"] == null ? null : json["isAccepted"],
isFlexwerker: json["isFlexwerker"],
);
Map<String, dynamic> toJson() =>
{
"docentID": docentId == null ? null : docentId,
"naam": naam == null ? null : naam,
"achternaam": achternaam == null ? null : achternaam,
"emailadres": emailadres == null ? null : emailadres,
"geboortedatum": geboortedatum == null ? null : geboortedatum,
"geboorteplaats": geboorteplaats == null ? null : geboorteplaats,
"maxRijafstand": maxRijafstand,
"heeftRijbewijs": heeftRijbewijs,
"heeftAuto": heeftAuto,
"straat": straat == null ? null : straat,
"huisnummer": huisnummer == null ? null : huisnummer,
"geslacht": geslacht == null ? null : geslacht,
"nationaliteit": nationaliteit == null ? null : nationaliteit,
"woonplaats": woonplaats == null ? null : woonplaats,
"postcode": postcode == null ? null : postcode,
"land": land == null ? null : land,
"wachtwoord": wachtwoord == null ? null : wachtwoord,
"isAccepted": isAccepted == null ? null : isAccepted,
"isFlexwerker": isFlexwerker,
};
}
APIService class
class ApiService {
Future<List<UserModel>> getUsers() async {
try {
var url = Uri.parse(apis.baseUrl + apis.getUsers);
var response = await http.get(url);
if (response.statusCode == 200) {
List<UserModel> model = userModelFromJson(response.body);
return model;
}
} catch (e) {
log(e.toString());
}
}
}
Results from the API to list all the imported users
{
"status": 200,
"result": [
{
"docentID": 1,
"naam": "gerrit",
"achternaam": "petersen",
"emailadres": "meel#meel.com",
"geboortedatum": "1899-11-29T23:40:28.000Z",
"geboorteplaats": "",
"maxRijafstand": null,
"heeftRijbewijs": null,
"heeftAuto": null,
"straat": "",
"huisnummer": 0,
"geslacht": "",
"nationaliteit": "",
"woonplaats": "",
"postcode": "",
"land": "",
"wachtwoord": "$2b$10$kcVpe9yOdKzMPdEUcMIATOh3PE42GDiQfDLZeufKxpLpTb51Af7Ay",
"isAccepted": 0,
"isFlexwerker": null
},
{
"docentID": 4,
"naam": "gerrit",
"achternaam": "petersen",
"emailadres": "123mail123#meel.com",
"geboortedatum": "1899-11-29T23:40:28.000Z",
"geboorteplaats": "",
"maxRijafstand": null,
"heeftRijbewijs": null,
"heeftAuto": null,
"straat": "",
"huisnummer": 0,
"geslacht": "",
"nationaliteit": "",
"woonplaats": "",
"postcode": "",
"land": "",
"wachtwoord": "$2b$10$jNx8CrBRw78VZdoTTomGWuVF4CEa6wcMMsIzmkHak1WjRVsfHaX86",
"isAccepted": 0,
"isFlexwerker": null
},
{
"docentID": 7,
"naam": "Peter",
"achternaam": "gerritsen",
"emailadres": "test1#meel.com",
"geboortedatum": "1899-11-29T23:40:28.000Z",
"geboorteplaats": "",
"maxRijafstand": null,
"heeftRijbewijs": null,
"heeftAuto": null,
"straat": "",
"huisnummer": 0,
"geslacht": "",
"nationaliteit": "",
"woonplaats": "",
"postcode": "",
"land": "",
"wachtwoord": "$2b$10$JRbNe40U7Fk2hcA4B4bgEe9ElmCX5dCovf5FNtZTLHLCX8v/DeiN2",
"isAccepted": 0,
"isFlexwerker": null
}
]
}
I am trying to get the data from my json feed which is this Json
But when I try to use the body result it is not working ( but it works with other jsons like this one https://jsonplaceholder.typicode.com/users), my code looks like this:
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'noticias.dart';
class Services {
static const String url =
'https://studiofutbol.com.ec/api/json/feed_master.php?pagina=';
static Future<Portada> getNoticias() async {
try {
var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest',
};
final response = await http.get(url, headers: headers);
debugPrint(response.body);
if (200 == response.statusCode) {
final Portada noticiasportada = portadaFromJson(response.body);
return noticiasportada;
} else {
return Portada();
}
} catch (e) {
return Portada();
}
}
}
I added those headers but it did not help, what could be causing the issue?
It work for me like this
Future<Portada> getNoticias() async {
try {
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.getUrl(Uri.parse(
"https://studiofutbol.com.ec/api/json/feed_master.php?pagina="));
request.headers.set('content-type', 'application/json');
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply);
httpClient.close();
Map<String, dynamic> map = json.decode(reply);
final Portada noticiasportada = Portada.fromMap(map);
return noticiasportada;
} catch (e) {
return Portada();
}
}
Model Class
import 'dart:convert';
Portada portadaFromMap(String str) => Portada.fromMap(json.decode(str));
String portadaToMap(Portada data) => json.encode(data.toMap());
class Portada {
Portada({
this.json,
this.menu,
this.banners,
this.tags,
this.equipos,
this.menuIos,
this.version,
this.versionIos,
});
List<Json> json;
List<Menu> menu;
Banners banners;
List<Tag> tags;
List<Equipo> equipos;
List<MenuIo> menuIos;
String version;
String versionIos;
factory Portada.fromMap(Map<String, dynamic> json) => Portada(
json: json["Json"] == null ? null : List<Json>.from(json["Json"].map((x) => Json.fromMap(x))),
menu: json["menu"] == null ? null : List<Menu>.from(json["menu"].map((x) => Menu.fromMap(x))),
banners: json["banners"] == null ? null : Banners.fromMap(json["banners"]),
tags: json["tags"] == null ? null : List<Tag>.from(json["tags"].map((x) => Tag.fromMap(x))),
equipos: json["equipos"] == null ? null : List<Equipo>.from(json["equipos"].map((x) => Equipo.fromMap(x))),
menuIos: json["menu_ios"] == null ? null : List<MenuIo>.from(json["menu_ios"].map((x) => MenuIo.fromMap(x))),
version: json["version"] == null ? null : json["version"],
versionIos: json["version_ios"] == null ? null : json["version_ios"],
);
Map<String, dynamic> toMap() => {
"Json": json == null ? null : List<dynamic>.from(json.map((x) => x.toMap())),
"menu": menu == null ? null : List<dynamic>.from(menu.map((x) => x.toMap())),
"banners": banners == null ? null : banners.toMap(),
"tags": tags == null ? null : List<dynamic>.from(tags.map((x) => x.toMap())),
"equipos": equipos == null ? null : List<dynamic>.from(equipos.map((x) => x.toMap())),
"menu_ios": menuIos == null ? null : List<dynamic>.from(menuIos.map((x) => x.toMap())),
"version": version == null ? null : version,
"version_ios": versionIos == null ? null : versionIos,
};
}
class Banners {
Banners({
this.splash,
this.splashiphone,
this.main,
this.interna,
});
Interna splash;
Interna splashiphone;
Interna main;
Interna interna;
factory Banners.fromMap(Map<String, dynamic> json) => Banners(
splash: json["splash"] == null ? null : Interna.fromMap(json["splash"]),
splashiphone: json["splashiphone"] == null ? null : Interna.fromMap(json["splashiphone"]),
main: json["main"] == null ? null : Interna.fromMap(json["main"]),
interna: json["interna"] == null ? null : Interna.fromMap(json["interna"]),
);
Map<String, dynamic> toMap() => {
"splash": splash == null ? null : splash.toMap(),
"splashiphone": splashiphone == null ? null : splashiphone.toMap(),
"main": main == null ? null : main.toMap(),
"interna": interna == null ? null : interna.toMap(),
};
}
class Interna {
Interna({
this.imagen,
this.link,
});
String imagen;
String link;
factory Interna.fromMap(Map<String, dynamic> json) => Interna(
imagen: json["imagen"] == null ? null : json["imagen"],
link: json["link"] == null ? null : json["link"],
);
Map<String, dynamic> toMap() => {
"imagen": imagen == null ? null : imagen,
"link": link == null ? null : link,
};
}
class Equipo {
Equipo({
this.id,
this.nombre,
});
int id;
String nombre;
factory Equipo.fromMap(Map<String, dynamic> json) => Equipo(
id: json["id"] == null ? null : json["id"],
nombre: json["nombre"] == null ? null : json["nombre"],
);
Map<String, dynamic> toMap() => {
"id": id == null ? null : id,
"nombre": nombre == null ? null : nombre,
};
}
class Json {
Json({
this.id,
this.title,
this.titleint,
this.permalink,
this.content,
this.excerpt,
this.date,
this.author,
this.image,
this.fuente,
this.thumbnail,
this.categories,
this.tags,
this.contentIphone,
this.videoEnlace,
});
int id;
String title;
String titleint;
String permalink;
String content;
String excerpt;
DateTime date;
String author;
List<dynamic> image;
String fuente;
String thumbnail;
List<String> categories;
List<String> tags;
String contentIphone;
String videoEnlace;
factory Json.fromMap(Map<String, dynamic> json) => Json(
id: json["id"] == null ? null : json["id"],
title: json["title"] == null ? null : json["title"],
titleint: json["titleint"] == null ? null : json["titleint"],
permalink: json["permalink"] == null ? null : json["permalink"],
content: json["content"] == null ? null : json["content"],
excerpt: json["excerpt"] == null ? null : json["excerpt"],
date: json["date"] == null ? null : DateTime.parse(json["date"]),
author: json["author"] == null ? null : json["author"],
image: json["image"] == null ? null : List<dynamic>.from(json["image"].map((x) => x)),
fuente: json["fuente"] == null ? null : json["fuente"],
thumbnail: json["thumbnail"] == null ? null : json["thumbnail"],
categories: json["categories"] == null ? null : List<String>.from(json["categories"].map((x) => x)),
tags: json["tags"] == null ? null : List<String>.from(json["tags"].map((x) => x)),
contentIphone: json["contentIphone"] == null ? null : json["contentIphone"],
videoEnlace: json["video_enlace"] == null ? null : json["video_enlace"],
);
Map<String, dynamic> toMap() => {
"id": id == null ? null : id,
"title": title == null ? null : title,
"titleint": titleint == null ? null : titleint,
"permalink": permalink == null ? null : permalink,
"content": content == null ? null : content,
"excerpt": excerpt == null ? null : excerpt,
"date": date == null ? null : date.toIso8601String(),
"author": author == null ? null : author,
"image": image == null ? null : List<dynamic>.from(image.map((x) => x)),
"fuente": fuente == null ? null : fuente,
"thumbnail": thumbnail == null ? null : thumbnail,
"categories": categories == null ? null : List<dynamic>.from(categories.map((x) => x)),
"tags": tags == null ? null : List<dynamic>.from(tags.map((x) => x)),
"contentIphone": contentIphone == null ? null : contentIphone,
"video_enlace": videoEnlace == null ? null : videoEnlace,
};
}
class Menu {
Menu({
this.url,
this.nombre,
});
String url;
String nombre;
factory Menu.fromMap(Map<String, dynamic> json) => Menu(
url: json["url"] == null ? null : json["url"],
nombre: json["nombre"] == null ? null : json["nombre"],
);
Map<String, dynamic> toMap() => {
"url": url == null ? null : url,
"nombre": nombre == null ? null : nombre,
};
}
class MenuIo {
MenuIo({
this.nombre,
this.url,
this.segue,
this.img,
});
String nombre;
String url;
String segue;
String img;
factory MenuIo.fromMap(Map<String, dynamic> json) => MenuIo(
nombre: json["nombre"] == null ? null : json["nombre"],
url: json["url"] == null ? null : json["url"],
segue: json["segue"] == null ? null : json["segue"],
img: json["img"] == null ? null : json["img"],
);
Map<String, dynamic> toMap() => {
"nombre": nombre == null ? null : nombre,
"url": url == null ? null : url,
"segue": segue == null ? null : segue,
"img": img == null ? null : img,
};
}
class Tag {
Tag({
this.id,
this.nombre,
this.url,
});
int id;
String nombre;
String url;
factory Tag.fromMap(Map<String, dynamic> json) => Tag(
id: json["id"] == null ? null : json["id"],
nombre: json["nombre"] == null ? null : json["nombre"],
url: json["url"] == null ? null : json["url"],
);
Map<String, dynamic> toMap() => {
"id": id == null ? null : id,
"nombre": nombre == null ? null : nombre,
"url": url == null ? null : url,
};
}
I have this model
class Meal {
Meal({
this.strMeal,
this.strMealThumb,
this.idMeal,
});
String strMeal;
String strMealThumb;
String idMeal;
factory Meal.fromJson(Map<String, dynamic> json) => Meal(
strMeal: json["strMeal"],
strMealThumb: json["strMealThumb"],
idMeal: json["idMeal"],
);
}
with help of the HTTP package on flutter, I'm making this request:
class RemoteServices {
static var client = http.Client();
static Future<Meal> fetchMealById(String id) async {
var response = await client
.get('https://www.themealdb.com/api/json/v1/1/lookup.php?i=52772');
if (response.statusCode == 200) {
var jasonStr = response.body;
print("f" + jasonStr);
Meal meal = Meal.fromJson(json.decode(response.body));
print(meal.idMeal);
} else {
throw Exception("Unable to Load");
}
}
}
I'm getting a Null value after decoding the response, although the response body before decoding is not null and contain an object that holds my data
You can copy paste run full code below
Data returned from your url is List<Meal> not Meal
You can reference model detail in full code
code snippet
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
class Payload {
Payload({
this.meals,
});
List<Meal> meals;
...
static Future<List<Meal>> fetchMealById(String id) async {
print(id);
var response = await client
.get('https://www.themealdb.com/api/json/v1/1/lookup.php?i=52772');
if (response.statusCode == 200) {
var jasonStr = response.body;
print("f" + jasonStr);
Payload payload = payloadFromJson(response.body);
return payload.meals;
...
FutureBuilder(
future: _future("yourId"),
builder: (context, AsyncSnapshot<List<Meal>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
print(snapshot.data.runtimeType);
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Card(
elevation: 6.0,
child: Padding(
padding: const EdgeInsets.only(
top: 6.0,
bottom: 6.0,
left: 8.0,
right: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
snapshot.data[index].idMeal.toString()),
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
Payload({
this.meals,
});
List<Meal> meals;
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
meals: json["meals"] == null
? null
: List<Meal>.from(json["meals"].map((x) => Meal.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"meals": meals == null
? null
: List<dynamic>.from(meals.map((x) => x.toJson())),
};
}
class Meal {
Meal({
this.idMeal,
this.strMeal,
this.strDrinkAlternate,
this.strCategory,
this.strArea,
this.strInstructions,
this.strMealThumb,
this.strTags,
this.strYoutube,
this.strIngredient1,
this.strIngredient2,
this.strIngredient3,
this.strIngredient4,
this.strIngredient5,
this.strIngredient6,
this.strIngredient7,
this.strIngredient8,
this.strIngredient9,
this.strIngredient10,
this.strIngredient11,
this.strIngredient12,
this.strIngredient13,
this.strIngredient14,
this.strIngredient15,
this.strIngredient16,
this.strIngredient17,
this.strIngredient18,
this.strIngredient19,
this.strIngredient20,
this.strMeasure1,
this.strMeasure2,
this.strMeasure3,
this.strMeasure4,
this.strMeasure5,
this.strMeasure6,
this.strMeasure7,
this.strMeasure8,
this.strMeasure9,
this.strMeasure10,
this.strMeasure11,
this.strMeasure12,
this.strMeasure13,
this.strMeasure14,
this.strMeasure15,
this.strMeasure16,
this.strMeasure17,
this.strMeasure18,
this.strMeasure19,
this.strMeasure20,
this.strSource,
this.dateModified,
});
String idMeal;
String strMeal;
dynamic strDrinkAlternate;
String strCategory;
String strArea;
String strInstructions;
String strMealThumb;
String strTags;
String strYoutube;
String strIngredient1;
String strIngredient2;
String strIngredient3;
String strIngredient4;
String strIngredient5;
String strIngredient6;
String strIngredient7;
String strIngredient8;
String strIngredient9;
String strIngredient10;
String strIngredient11;
String strIngredient12;
String strIngredient13;
String strIngredient14;
String strIngredient15;
dynamic strIngredient16;
dynamic strIngredient17;
dynamic strIngredient18;
dynamic strIngredient19;
dynamic strIngredient20;
String strMeasure1;
String strMeasure2;
String strMeasure3;
String strMeasure4;
String strMeasure5;
String strMeasure6;
String strMeasure7;
String strMeasure8;
String strMeasure9;
String strMeasure10;
String strMeasure11;
String strMeasure12;
String strMeasure13;
String strMeasure14;
String strMeasure15;
dynamic strMeasure16;
dynamic strMeasure17;
dynamic strMeasure18;
dynamic strMeasure19;
dynamic strMeasure20;
dynamic strSource;
dynamic dateModified;
factory Meal.fromJson(Map<String, dynamic> json) => Meal(
idMeal: json["idMeal"] == null ? null : json["idMeal"],
strMeal: json["strMeal"] == null ? null : json["strMeal"],
strDrinkAlternate: json["strDrinkAlternate"],
strCategory: json["strCategory"] == null ? null : json["strCategory"],
strArea: json["strArea"] == null ? null : json["strArea"],
strInstructions:
json["strInstructions"] == null ? null : json["strInstructions"],
strMealThumb:
json["strMealThumb"] == null ? null : json["strMealThumb"],
strTags: json["strTags"] == null ? null : json["strTags"],
strYoutube: json["strYoutube"] == null ? null : json["strYoutube"],
strIngredient1:
json["strIngredient1"] == null ? null : json["strIngredient1"],
strIngredient2:
json["strIngredient2"] == null ? null : json["strIngredient2"],
strIngredient3:
json["strIngredient3"] == null ? null : json["strIngredient3"],
strIngredient4:
json["strIngredient4"] == null ? null : json["strIngredient4"],
strIngredient5:
json["strIngredient5"] == null ? null : json["strIngredient5"],
strIngredient6:
json["strIngredient6"] == null ? null : json["strIngredient6"],
strIngredient7:
json["strIngredient7"] == null ? null : json["strIngredient7"],
strIngredient8:
json["strIngredient8"] == null ? null : json["strIngredient8"],
strIngredient9:
json["strIngredient9"] == null ? null : json["strIngredient9"],
strIngredient10:
json["strIngredient10"] == null ? null : json["strIngredient10"],
strIngredient11:
json["strIngredient11"] == null ? null : json["strIngredient11"],
strIngredient12:
json["strIngredient12"] == null ? null : json["strIngredient12"],
strIngredient13:
json["strIngredient13"] == null ? null : json["strIngredient13"],
strIngredient14:
json["strIngredient14"] == null ? null : json["strIngredient14"],
strIngredient15:
json["strIngredient15"] == null ? null : json["strIngredient15"],
strIngredient16: json["strIngredient16"],
strIngredient17: json["strIngredient17"],
strIngredient18: json["strIngredient18"],
strIngredient19: json["strIngredient19"],
strIngredient20: json["strIngredient20"],
strMeasure1: json["strMeasure1"] == null ? null : json["strMeasure1"],
strMeasure2: json["strMeasure2"] == null ? null : json["strMeasure2"],
strMeasure3: json["strMeasure3"] == null ? null : json["strMeasure3"],
strMeasure4: json["strMeasure4"] == null ? null : json["strMeasure4"],
strMeasure5: json["strMeasure5"] == null ? null : json["strMeasure5"],
strMeasure6: json["strMeasure6"] == null ? null : json["strMeasure6"],
strMeasure7: json["strMeasure7"] == null ? null : json["strMeasure7"],
strMeasure8: json["strMeasure8"] == null ? null : json["strMeasure8"],
strMeasure9: json["strMeasure9"] == null ? null : json["strMeasure9"],
strMeasure10:
json["strMeasure10"] == null ? null : json["strMeasure10"],
strMeasure11:
json["strMeasure11"] == null ? null : json["strMeasure11"],
strMeasure12:
json["strMeasure12"] == null ? null : json["strMeasure12"],
strMeasure13:
json["strMeasure13"] == null ? null : json["strMeasure13"],
strMeasure14:
json["strMeasure14"] == null ? null : json["strMeasure14"],
strMeasure15:
json["strMeasure15"] == null ? null : json["strMeasure15"],
strMeasure16: json["strMeasure16"],
strMeasure17: json["strMeasure17"],
strMeasure18: json["strMeasure18"],
strMeasure19: json["strMeasure19"],
strMeasure20: json["strMeasure20"],
strSource: json["strSource"],
dateModified: json["dateModified"],
);
Map<String, dynamic> toJson() => {
"idMeal": idMeal == null ? null : idMeal,
"strMeal": strMeal == null ? null : strMeal,
"strDrinkAlternate": strDrinkAlternate,
"strCategory": strCategory == null ? null : strCategory,
"strArea": strArea == null ? null : strArea,
"strInstructions": strInstructions == null ? null : strInstructions,
"strMealThumb": strMealThumb == null ? null : strMealThumb,
"strTags": strTags == null ? null : strTags,
"strYoutube": strYoutube == null ? null : strYoutube,
"strIngredient1": strIngredient1 == null ? null : strIngredient1,
"strIngredient2": strIngredient2 == null ? null : strIngredient2,
"strIngredient3": strIngredient3 == null ? null : strIngredient3,
"strIngredient4": strIngredient4 == null ? null : strIngredient4,
"strIngredient5": strIngredient5 == null ? null : strIngredient5,
"strIngredient6": strIngredient6 == null ? null : strIngredient6,
"strIngredient7": strIngredient7 == null ? null : strIngredient7,
"strIngredient8": strIngredient8 == null ? null : strIngredient8,
"strIngredient9": strIngredient9 == null ? null : strIngredient9,
"strIngredient10": strIngredient10 == null ? null : strIngredient10,
"strIngredient11": strIngredient11 == null ? null : strIngredient11,
"strIngredient12": strIngredient12 == null ? null : strIngredient12,
"strIngredient13": strIngredient13 == null ? null : strIngredient13,
"strIngredient14": strIngredient14 == null ? null : strIngredient14,
"strIngredient15": strIngredient15 == null ? null : strIngredient15,
"strIngredient16": strIngredient16,
"strIngredient17": strIngredient17,
"strIngredient18": strIngredient18,
"strIngredient19": strIngredient19,
"strIngredient20": strIngredient20,
"strMeasure1": strMeasure1 == null ? null : strMeasure1,
"strMeasure2": strMeasure2 == null ? null : strMeasure2,
"strMeasure3": strMeasure3 == null ? null : strMeasure3,
"strMeasure4": strMeasure4 == null ? null : strMeasure4,
"strMeasure5": strMeasure5 == null ? null : strMeasure5,
"strMeasure6": strMeasure6 == null ? null : strMeasure6,
"strMeasure7": strMeasure7 == null ? null : strMeasure7,
"strMeasure8": strMeasure8 == null ? null : strMeasure8,
"strMeasure9": strMeasure9 == null ? null : strMeasure9,
"strMeasure10": strMeasure10 == null ? null : strMeasure10,
"strMeasure11": strMeasure11 == null ? null : strMeasure11,
"strMeasure12": strMeasure12 == null ? null : strMeasure12,
"strMeasure13": strMeasure13 == null ? null : strMeasure13,
"strMeasure14": strMeasure14 == null ? null : strMeasure14,
"strMeasure15": strMeasure15 == null ? null : strMeasure15,
"strMeasure16": strMeasure16,
"strMeasure17": strMeasure17,
"strMeasure18": strMeasure18,
"strMeasure19": strMeasure19,
"strMeasure20": strMeasure20,
"strSource": strSource,
"dateModified": dateModified,
};
}
class RemoteServices {
static var client = http.Client();
static Future<List<Meal>> fetchMealById(String id) async {
print(id);
var response = await client
.get('https://www.themealdb.com/api/json/v1/1/lookup.php?i=52772');
if (response.statusCode == 200) {
var jasonStr = response.body;
print("f" + jasonStr);
Payload payload = payloadFromJson(response.body);
//Meal meal = Meal.fromJson(json.decode(response.body));
print(payload.meals.length);
print(payload.meals);
return payload.meals;
} else {
throw Exception("Unable to Load");
}
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
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> {
Function _future;
#override
void initState() {
_future = RemoteServices.fetchMealById;
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: _future("yourId"),
builder: (context, AsyncSnapshot<List<Meal>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
print(snapshot.data.runtimeType);
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Card(
elevation: 6.0,
child: Padding(
padding: const EdgeInsets.only(
top: 6.0,
bottom: 6.0,
left: 8.0,
right: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
snapshot.data[index].idMeal.toString()),
Spacer(),
Text(
snapshot.data[index].strCategory,
),
],
),
));
});
}
}
}));
}
}
So I am trying to parse some json with http my method of parsing in this
Future<bool> fetchUser(username) async {
setLoading(true);
await Osu(username).fetchUser().then((data) {
setLoading(false);
if (data.statusCode == 200) {
setUser(UserInfo.fromJson(json.decode(data.body)));
} else {
print(data.body);
Map<String, dynamic> result = json.decode(data.body);
setMessage(result['message']);
}
});
return isUser();
}
class UserInfo {
String userId;
String username;
DateTime joinDate;
String count300;
String count100;
String count50;
String playcount;
String rankedScore;
String totalScore;
String ppRank;
String level;
String ppRaw;
String accuracy;
String countRankSs;
String countRankSsh;
String countRankS;
String countRankSh;
String countRankA;
String country;
String totalSecondsPlayed;
String ppCountryRank;
List<dynamic> events;
UserInfo({
this.userId,
this.username,
this.joinDate,
this.count300,
this.count100,
this.count50,
this.playcount,
this.rankedScore,
this.totalScore,
this.ppRank,
this.level,
this.ppRaw,
this.accuracy,
this.countRankSs,
this.countRankSsh,
this.countRankS,
this.countRankSh,
this.countRankA,
this.country,
this.totalSecondsPlayed,
this.ppCountryRank,
this.events,
});
Map toJson() => {
"user_id": userId == null ? null : userId,
"username": username == null ? null : username,
"join_date": joinDate == null ? null : joinDate.toIso8601String(),
"count300": count300 == null ? null : count300,
"count100": count100 == null ? null : count100,
"count50": count50 == null ? null : count50,
"playcount": playcount == null ? null : playcount,
"ranked_score": rankedScore == null ? null : rankedScore,
"total_score": totalScore == null ? null : totalScore,
"pp_rank": ppRank == null ? null : ppRank,
"level": level == null ? null : level,
"pp_raw": ppRaw == null ? null : ppRaw,
"accuracy": accuracy == null ? null : accuracy,
"count_rank_ss": countRankSs == null ? null : countRankSs,
"count_rank_ssh": countRankSsh == null ? null : countRankSsh,
"count_rank_s": countRankS == null ? null : countRankS,
"count_rank_sh": countRankSh == null ? null : countRankSh,
"count_rank_a": countRankA == null ? null : countRankA,
"country": country == null ? null : country,
"total_seconds_played":
totalSecondsPlayed == null ? null : totalSecondsPlayed,
"pp_country_rank": ppCountryRank == null ? null : ppCountryRank,
"events":
events == null ? null : List<dynamic>.from(events.map((x) => x)),
};
UserInfo.fromJson(Map json)
: userId = json["user_id"] == null ? null : json["user_id"],
username = json["username"] == null ? null : json["username"],
joinDate = json["join_date"] == null
? null
: DateTime.parse(json["join_date"]),
count300 = json["count300"] == null ? null : json["count300"],
count100 = json["count100"] == null ? null : json["count100"],
count50 = json["count50"] == null ? null : json["count50"],
playcount = json["playcount"] == null ? null : json["playcount"],
rankedScore =
json["ranked_score"] == null ? null : json["ranked_score"],
totalScore = json["total_score"] == null ? null : json["total_score"],
ppRank = json["pp_rank"] == null ? null : json["pp_rank"],
level = json["level"] == null ? null : json["level"],
ppRaw = json["pp_raw"] == null ? null : json["pp_raw"],
accuracy = json["accuracy"] == null ? null : json["accuracy"],
countRankSs =
json["count_rank_ss"] == null ? null : json["count_rank_ss"],
countRankSsh =
json["count_rank_ssh"] == null ? null : json["count_rank_ssh"],
countRankS = json["count_rank_s"] == null ? null : json["count_rank_s"],
countRankSh =
json["count_rank_sh"] == null ? null : json["count_rank_sh"],
countRankA = json["count_rank_a"] == null ? null : json["count_rank_a"],
country = json["country"] == null ? null : json["country"],
totalSecondsPlayed = json["total_seconds_played"] == null
? null
: json["total_seconds_played"],
ppCountryRank =
json["pp_country_rank"] == null ? null : json["pp_country_rank"],
events = json["events"] == null
? null
: List<dynamic>.from(json["events"].map((x) => x));
}
And then this is my request call:
import 'package:http/http.dart' as http;
class Osu {
final String userName;
final String url = 'https://osu.ppy.sh/api';
static String apiKey = 'wewewewewwweojjfoejfe';
Osu(this.userName);
Future<http.Response> fetchUser() {
return http.get(url + '/get_user' + "?u=$userName" + "&k=$apiKey");
}
}
I have tried returning it in a list but i just get the same error and advice?
The error I get is:
TypeError (type 'List' is not a subtype of type 'Map')
on line
await Osu(username).fetchUser().then((data) {
Thank you!
I am not sure if it is not mapping correctly or that I am messing up the call itself. Either way I have been extremely stumped on this for the past 30m and can't seem to solve it.
Updated with json:
[
{
"user_id": "9795284",
"username": "SakuraMotion",
"join_date": "2017-02-24 17:41:13",
"count300": "4155343",
"count100": "655286",
"count50": "64939",
"playcount": "25758",
"ranked_score": "8433289241",
"total_score": "20762480956",
"pp_rank": "84925",
"level": "99.3314",
"pp_raw": "3318.78",
"accuracy": "95.20140075683594",
"count_rank_ss": "5",
"count_rank_ssh": "0",
"count_rank_s": "473",
"count_rank_sh": "1",
"count_rank_a": "942",
"country": "US",
"total_seconds_played": "1467366",
"pp_country_rank": "14317",
"events": []
}
updated with data.body response:
[
{
"user_id": "9795284",
"username": "SakuraMotion",
"join_date": "2017-02-24 17:41:13",
"count300": "4185533",
"count100": "658232",
"count50": "65063",
"playcount": "26008",
"ranked_score": "8509686083",
"total_score": "20977676803",
"pp_rank": "84295",
"level": "99.3547",
"pp_raw": "3333.68",
"accuracy": "95.1374740600586",
"count_rank_ss": "5",
"count_rank_ssh": "0",
"count_rank_s": "477",
"count_rank_sh": "1",
"count_rank_a": "950",
"country": "US",
"total_seconds_played": "1475942",
"pp_country_rank": "14224",
"events": [
{
"display_html": "<img src='/images/C_small.png'/> <b><a href='/u/9795284'>SakuraMotion</a></b> achieved rank #842 on <a href='/b/1771455?m=3'>Cranky vs. MASAKI - ouroboros -twin stroke of the end- [4K CS' Normal]</a> (osu!mania)",
"beatmap_id": "1771455",
"beatmapset_id": "845135",
"date": "2019-10-19 01:24:15",
"epicfactor": "1"
},
{
"display_html": "<img src='/images/B_small.png'/> <b><a href='/u/9795284'>SakuraMotion</a></b> achieved rank #812 on <a href='/b/2115037?m=0'>Kousaka Honoka (CV: Nitta Emi) - Snow halation (HONOKA Mix) [Devotion]</a> (osu!)",
"beatmap_id": "2115037",
"beatmapset_id": "982344",
"date": "2019-10-19 01:08:44",
"epicfactor": "1"
},
{
"display_html": "<img src='/images/B_small.png'/> <b><a href='/u/9795284'>SakuraMotion</a></b> achieved rank #377 on <a href='/b/2173646?m=0'>Roselia - Charles [Expert]</a> (osu!)",
"beatmap_id": "2173646",
"beatmapset_id": "1032239",
"date": "2019-10-19 01:05:46",
"epicfactor": "1"
},
{
"display_html": "<img src='/images/B_small.png'/> <b><a href='/u/9795284'>SakuraMotion</a></b> achieved rank #70 on <a href='/b/2123647?m=0'>Reol - Jitter Doll [Extra]</a> (osu!)",
"beatmap_id": "2123647",
"beatmapset_id": "1010993",
"date": "2019-10-19 01:02:50",
"epicfactor": "1"
}
]
}
]
Pay attention to the error as it is clearly stating your issue: type 'List<dynamic>' is not a subtype of type 'Map, not sure if it is actually on fetch but
Find documentation for https://osu.ppy.sh/api/get_user API and confirm response. You can also test command line by doing:
curl -X GET https://osu.ppy.sh/api/get_user&u=USERNAME&k=KEY
and ensure you are getting 200 and correct structure.
I think the error is on this line
Map<String, dynamic> result = json.decode(data.body);
The result of the json.decode(data.body) is actually a List but you assigned it to Map
I think you can change it to
List<Dynamic> result = json.decode(data.body);
or
List result = json.decode(data.body);
If you really need to Map it, you can Map it later from the List
There is a multitude of reasons that you might be getting the error... it would be beneficial to provide a sample of the JSON that the API is returning.
You can check your UserInfo()... it has the following field:
List<dynamic> events;
Double check if the events coming from the JSON is really a List.
If you are having an issue with parsing complex JSON files... better use JsonSerializable https://flutter.dev/docs/development/data-and-backend/json#creating-model-classes-the-json_serializable-way