how to create an entity based on a model? - flutter

Tell me please. At first, I decided to make a simple application, but now I want to use a clean architecture and I need to know what my HomeEntity should look like. I have a model, it was generated by the site. And I also need all the fields of my model in my entity.
I can’t just use JUST all the fields that I described there, because some of them need to be “entered”
Here is my model -
// To parse this JSON data, do
//
// final plan = planFromJson(jsonString);
import 'dart:convert';
Plan planFromJson(String str) => Plan.fromJson(json.decode(str));
String planToJson(Plan data) => json.encode(data.toJson());
class Plan {
Plan({
required this.data,
required this.meta,
});
List<Datum> data;
Meta meta;
factory Plan.fromJson(Map<String, dynamic> json) => Plan(
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
meta: Meta.fromJson(json["meta"]),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"meta": meta.toJson(),
};
}
class Datum {
Datum({
required this.id,
required this.attributes,
});
int id;
DatumAttributes attributes;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
attributes: DatumAttributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"attributes": attributes.toJson(),
};
}
class DatumAttributes {
DatumAttributes({
required this.header,
required this.description,
required this.added,
required this.createdAt,
required this.updatedAt,
required this.publishedAt,
required this.image,
});
String header;
String description;
bool added;
DateTime createdAt;
DateTime updatedAt;
DateTime publishedAt;
Image image;
factory DatumAttributes.fromJson(Map<String, dynamic> json) => DatumAttributes(
header: json["header"],
description: json["description"],
added: json["added"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
publishedAt: DateTime.parse(json["publishedAt"]),
image: Image.fromJson(json["image"]),
);
Map<String, dynamic> toJson() => {
"header": header,
"description": description,
"added": added,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
"publishedAt": publishedAt.toIso8601String(),
"image": image.toJson(),
};
}
class Image {
Image({
required this.data,
});
Data data;
factory Image.fromJson(Map<String, dynamic> json) => Image(
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"data": data.toJson(),
};
}
class Data {
Data({
required this.id,
required this.attributes,
});
int id;
DataAttributes attributes;
factory Data.fromJson(Map<String, dynamic> json) => Data(
id: json["id"],
attributes: DataAttributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"attributes": attributes.toJson(),
};
}
class DataAttributes {
DataAttributes({
required this.name,
required this.alternativeText,
required this.caption,
required this.width,
required this.height,
required this.formats,
required this.hash,
required this.ext,
required this.mime,
required this.size,
required this.url,
required this.previewUrl,
required this.provider,
required this.providerMetadata,
required this.createdAt,
required this.updatedAt,
});
String name;
dynamic alternativeText;
dynamic caption;
int width;
int height;
Formats formats;
String hash;
Ext? ext;
Mime? mime;
double size;
String url;
dynamic previewUrl;
String provider;
dynamic providerMetadata;
DateTime createdAt;
DateTime updatedAt;
factory DataAttributes.fromJson(Map<String, dynamic> json) => DataAttributes(
name: json["name"],
alternativeText: json["alternativeText"],
caption: json["caption"],
width: json["width"],
height: json["height"],
formats: Formats.fromJson(json["formats"]),
hash: json["hash"],
ext: extValues.map[json["ext"]],
mime: mimeValues.map[json["mime"]],
size: json["size"].toDouble(),
url: json["url"],
previewUrl: json["previewUrl"],
provider: json["provider"],
providerMetadata: json["provider_metadata"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
);
Map<String, dynamic> toJson() => {
"name": name,
"alternativeText": alternativeText,
"caption": caption,
"width": width,
"height": height,
"formats": formats.toJson(),
"hash": hash,
"ext": extValues.reverse[ext],
"mime": mimeValues.reverse[mime],
"size": size,
"url": url,
"previewUrl": previewUrl,
"provider": provider,
"provider_metadata": providerMetadata,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
};
}
enum Ext { JPG }
final extValues = EnumValues({
".jpg": Ext.JPG
});
class Formats {
Formats({
required this.thumbnail,
required this.small,
required this.medium,
required this.large,
});
Small thumbnail;
Small small;
Small? medium;
Small? large;
factory Formats.fromJson(Map<String, dynamic> json) => Formats(
thumbnail: Small.fromJson(json["thumbnail"]),
small: Small.fromJson(json["small"]),
medium: json["medium"] == null ? null : Small.fromJson(json["medium"]),
large: json["large"] == null ? null : Small.fromJson(json["large"]),
);
Map<String, dynamic> toJson() => {
"thumbnail": thumbnail.toJson(),
"small": small.toJson(),
"medium": medium == null ? null : medium?.toJson(),
"large": large == null ? null : large?.toJson(),
};
}
class Small {
Small({
required this.name,
required this.hash,
required this.ext,
required this.mime,
required this.path,
required this.width,
required this.height,
required this.size,
required this.url,
});
String name;
String hash;
Ext? ext;
Mime? mime;
dynamic path;
int width;
int height;
double size;
String url;
factory Small.fromJson(Map<String, dynamic> json) => Small(
name: json["name"],
hash: json["hash"],
ext: extValues.map[json["ext"]],
mime: mimeValues.map[json["mime"]],
path: json["path"],
width: json["width"],
height: json["height"],
size: json["size"].toDouble(),
url: json["url"],
);
Map<String, dynamic> toJson() => {
"name": name,
"hash": hash,
"ext": extValues.reverse[ext],
"mime": mimeValues.reverse[mime],
"path": path,
"width": width,
"height": height,
"size": size,
"url": url,
};
}
enum Mime { IMAGE_JPEG }
final mimeValues = EnumValues({
"image/jpeg": Mime.IMAGE_JPEG
});
class Meta {
Meta({
required this.pagination,
});
Pagination pagination;
factory Meta.fromJson(Map<String, dynamic> json) => Meta(
pagination: Pagination.fromJson(json["pagination"]),
);
Map<String, dynamic> toJson() => {
"pagination": pagination.toJson(),
};
}
class Pagination {
Pagination({
required this.page,
required this.pageSize,
required this.pageCount,
required this.total,
});
int page;
int pageSize;
int pageCount;
int total;
factory Pagination.fromJson(Map<String, dynamic> json) => Pagination(
page: json["page"],
pageSize: json["pageSize"],
pageCount: json["pageCount"],
total: json["total"],
);
Map<String, dynamic> toJson() => {
"page": page,
"pageSize": pageSize,
"pageCount": pageCount,
"total": total,
};
}
class EnumValues<T> {
Map<String, T> map;
late 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;
}
}
It will be cool if you help me create an entity for this model and explain the principle of how I can create it myself

define your class and its fields like this case:
class MobileViewModel {
final String countryCallingCode;
final String mobileNumber;
}
define the constructor of your class like this:
MobileViewModel({
required this.countryCallingCode,
required this.mobileNumber,
});
if you needs optional fields just remove requierd keyword and make your fields nullable.
then write fromJson method as a factory constructor.
(factory constructor returns an instance of your class from a json.)
factory MobileViewModel.fromJson(final Map<String, dynamic> json) =>
MobileViewModel(
countryCallingCode: json['countryCallingCode'],
mobileNumber: json['mobileNumber'],
);

Related

Failed to update album in flutter

I followed the flutter documentation on how to update API data and it worked, but when I tried to use the data API that I had when I updated, the result failed to load the album.
and the data API that I have has a different method, namely using POST.
is my code wrong?
Thank You.
Future<UserBiodata> getBiodata() async {
String url = Constant.baseURL;
String token = await UtilSharedPreferences.getToken();
final response = await http.get(
Uri.parse(
'$url/auth/mhs_siakad/biodata',
),
headers: {
'Authorization': 'Bearer $token',
},
);
print(response.statusCode);
print(response.body);
if (response.statusCode == 200) {
return UserBiodata.fromJson(jsonDecode(response.body));
} else {
throw Exception('Token Expired!');
}
}
Future<UserBiodata> updateBio(String email, String nik) async {
String url = Constant.baseURL;
String token = await UtilSharedPreferences.getToken();
final response = await http.post(
Uri.parse(
'$url/auth/mhs_siakad/biodata/update',
),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'email': email,
'nik': nik,
}),
);
if (response.statusCode == 200) {
return UserBiodata.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to update album.');
}
}
class UpdateBio extends StatefulWidget {
const UpdateBio({super.key});
#override
State<UpdateBio> createState() => _UpdateBioState();
}
class _UpdateBioState extends State<UpdateBio> {
final TextEditingController _controller = TextEditingController();
final TextEditingController _controller1 = TextEditingController();
late Future<UserBiodata> _futureBiodata;
#override
void initState() {
super.initState();
_futureBiodata = getBiodata();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: const Size.fromHeight(kToolbarHeight),
child: CustomAppbar(
title: 'Edit Biodata',
),
),
body: Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(8.0),
child: FutureBuilder<UserBiodata>(
future: _futureBiodata,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(snapshot.data!.data.email.toString()),
Text(snapshot.data!.data.nik.toString()),
TextField(
controller: _controller,
decoration: const InputDecoration(
hintText: 'Enter mail',
),
),
TextField(
controller: _controller1,
decoration: const InputDecoration(
hintText: 'Enter ID Card',
),
),
ElevatedButton(
onPressed: () {
setState(() {
_futureBiodata =
updateBio(_controller.text, _controller1.text);
});
},
child: const Text('Update Data'),
),
],
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
}
return const CircularProgressIndicator();
},
),
),
);
}
}
this is the model i have to update the data
import 'dart:convert';
UserBiodata userFromJson(String str) => UserBiodata.fromJson(json.decode(str));
String userToJson(UserBiodata data) => json.encode(data.toJson());
class UserBiodata {
UserBiodata({
required this.status,
required this.code,
required this.data,
});
String status;
String code;
Data data;
Data? dataUser;
factory UserBiodata.fromJson(Map<String, dynamic> json) => UserBiodata(
status: json["status"],
code: json["code"],
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"status": status,
"code": code,
"data": data.toJson(),
};
}
class Data {
Data({
required this.id,
required this.name,
required this.kelas,
required this.nim,
required this.prodi,
required this.ta,
required this.jk,
required this.status,
required this.stAgama,
required this.agama,
required this.stKwn,
required this.kwn,
required this.tempat,
required this.tglLahir,
required this.nik,
required this.nisn,
required this.npwp,
required this.jalan,
required this.stProv,
required this.province,
required this.stKab,
required this.kab,
required this.stKec,
required this.kec,
required this.desa,
required this.dusun,
required this.rt,
required this.rw,
required this.kodePos,
required this.telp,
required this.email,
required this.kps,
required this.stTrans,
required this.trans,
required this.stJn,
required this.jn,
required this.ipk,
required this.smt,
required this.namaAyah,
required this.nikAyah,
required this.tglLahirAyah,
required this.stPendidikanAyah,
required this.pendidikanAyah,
required this.pekerjaanAyah,
required this.penghasilanAyah,
required this.namaIbu,
required this.nikIbu,
required this.tglLahirIbu,
required this.stPendidikanIbu,
required this.pendidikanIbu,
required this.pekerjaanIbu,
required this.penghasilanIbu,
required this.namaWali,
required this.nikWali,
required this.tglLahirWali,
required this.stPendidikanWali,
required this.pendidikanWali,
this.pekerjaanWali,
this.penghasilanWali,
});
String id;
String name;
String kelas;
String nim;
String prodi;
String ta;
dynamic jk;
String status;
dynamic stAgama;
List<Agama> agama;
dynamic stKwn;
List<Kwn> kwn;
String tempat;
DateTime tglLahir;
String nik;
String nisn;
String npwp;
dynamic jalan;
dynamic stProv;
List<Kab> province;
dynamic stKab;
List<Kab> kab;
dynamic stKec;
List<Kab> kec;
dynamic desa;
dynamic dusun;
dynamic rt;
dynamic rw;
dynamic kodePos;
dynamic telp;
String email;
dynamic kps;
dynamic stTrans;
List<Tran> trans;
dynamic stJn;
List<Jn> jn;
String ipk;
int smt;
dynamic namaAyah;
dynamic nikAyah;
dynamic tglLahirAyah;
dynamic stPendidikanAyah;
List<Pendidikan> pendidikanAyah;
dynamic pekerjaanAyah;
dynamic penghasilanAyah;
String namaIbu;
String nikIbu;
dynamic tglLahirIbu;
dynamic stPendidikanIbu;
List<Pendidikan> pendidikanIbu;
dynamic pekerjaanIbu;
dynamic penghasilanIbu;
dynamic namaWali;
dynamic nikWali;
dynamic tglLahirWali;
dynamic stPendidikanWali;
List<Pendidikan> pendidikanWali;
dynamic pekerjaanWali;
dynamic penghasilanWali;
factory Data.fromJson(Map<String, dynamic> json) => Data(
id: json["id"],
name: json["name"],
kelas: json["kelas"],
nim: json["nim"],
prodi: json["prodi"],
ta: json["ta"],
jk: json["jk"],
status: json["status"],
stAgama: json["st_agama"],
agama: List<Agama>.from(json["agama"].map((x) => Agama.fromJson(x))),
stKwn: json["st_kwn"],
kwn: List<Kwn>.from(json["kwn"].map((x) => Kwn.fromJson(x))),
tempat: json["tempat"],
tglLahir: DateTime.parse(json["tgl_lahir"]),
nik: json["nik"],
nisn: json["nisn"],
npwp: json["npwp"],
jalan: json["jalan"],
stProv: json["st_prov"],
province: List<Kab>.from(json["province"].map((x) => Kab.fromJson(x))),
stKab: json["st_kab"],
kab: List<Kab>.from(json["kab"].map((x) => Kab.fromJson(x))),
stKec: json["st_kec"],
kec: List<Kab>.from(json["kec"].map((x) => Kab.fromJson(x))),
desa: json["desa"],
dusun: json["dusun"],
rt: json["rt"],
rw: json["rw"],
kodePos: json["kode_pos"],
telp: json["telp"],
email: json["email"],
kps: json["kps"],
stTrans: json["st_trans"],
trans: List<Tran>.from(json["trans"].map((x) => Tran.fromJson(x))),
stJn: json["st_jn"],
jn: List<Jn>.from(json["jn"].map((x) => Jn.fromJson(x))),
ipk: json["ipk"],
smt: json["smt"],
namaAyah: json["nama_ayah"],
nikAyah: json["nik_ayah"],
tglLahirAyah: json["tgl_lahir_ayah"],
stPendidikanAyah: json["st_pendidikan_ayah"],
pendidikanAyah: List<Pendidikan>.from(
json["pendidikan_ayah"].map((x) => Pendidikan.fromJson(x))),
pekerjaanAyah: json["pekerjaan_ayah"],
penghasilanAyah: json["penghasilan_ayah"],
namaIbu: json["nama_ibu"],
nikIbu: json["nik_ibu"],
tglLahirIbu: json["tgl_lahir_ibu"],
stPendidikanIbu: json["st_pendidikan_ibu"],
pendidikanIbu: List<Pendidikan>.from(
json["pendidikan_ibu"].map((x) => Pendidikan.fromJson(x))),
pekerjaanIbu: json["pekerjaan_ibu"],
penghasilanIbu: json["penghasilan_ibu"],
namaWali: json["nama_wali"],
nikWali: json["nik_wali"],
tglLahirWali: json["tgl_lahir_wali"],
stPendidikanWali: json["st_pendidikan_wali"],
pendidikanWali: List<Pendidikan>.from(
json["pendidikan_wali"].map((x) => Pendidikan.fromJson(x))),
pekerjaanWali: json["pekerjaan_wali"],
penghasilanWali: json["penghasilan_wali"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"kelas": kelas,
"nim": nim,
"prodi": prodi,
"ta": ta,
"jk": jk,
"status": status,
"st_agama": stAgama,
"agama": List<dynamic>.from(agama.map((x) => x.toJson())),
"st_kwn": stKwn,
"kwn": List<dynamic>.from(kwn.map((x) => x.toJson())),
"tempat": tempat,
"tgl_lahir":
"${tglLahir.year.toString().padLeft(4, '0')}-${tglLahir.month.toString().padLeft(2, '0')}-${tglLahir.day.toString().padLeft(2, '0')}",
"nik": nik,
"nisn": nisn,
"npwp": npwp,
"jalan": jalan,
"st_prov": stProv,
"province": List<dynamic>.from(province.map((x) => x.toJson())),
"st_kab": stKab,
"kab": List<dynamic>.from(kab.map((x) => x.toJson())),
"st_kec": stKec,
"kec": List<dynamic>.from(kec.map((x) => x.toJson())),
"desa": desa,
"dusun": dusun,
"rt": rt,
"rw": rw,
"kode_pos": kodePos,
"telp": telp,
"email": email,
"kps": kps,
"st_trans": stTrans,
"trans": List<dynamic>.from(trans.map((x) => x.toJson())),
"st_jn": stJn,
"jn": List<dynamic>.from(jn.map((x) => x.toJson())),
"ipk": ipk,
"smt": smt,
"nama_ayah": namaAyah,
"nik_ayah": nikAyah,
"tgl_lahir_ayah": tglLahirAyah,
"st_pendidikan_ayah": stPendidikanAyah,
"pendidikan_ayah":
List<dynamic>.from(pendidikanAyah.map((x) => x.toJson())),
"pekerjaan_ayah": pekerjaanAyah,
"penghasilan_ayah": penghasilanAyah,
"nama_ibu": namaIbu,
"nik_ibu": nikIbu,
"tgl_lahir_ibu": tglLahirIbu,
"st_pendidikan_ibu": stPendidikanIbu,
"pendidikan_ibu":
List<dynamic>.from(pendidikanIbu.map((x) => x.toJson())),
"pekerjaan_ibu": pekerjaanIbu,
"penghasilan_ibu": penghasilanIbu,
"nama_wali": namaWali,
"nik_wali": nikWali,
"tgl_lahir_wali": tglLahirWali,
"st_pendidikan_wali": stPendidikanWali,
"pendidikan_wali":
List<dynamic>.from(pendidikanWali.map((x) => x.toJson())),
"pekerjaan_wali": pekerjaanWali,
"penghasilan_wali": penghasilanWali,
};
}
class Agama {
Agama({
required this.id,
required this.idAgama,
required this.nmAgama,
required this.createdAt,
required this.updatedAt,
this.createdBy,
this.updatedBy,
});
String id;
String idAgama;
String nmAgama;
DateTime createdAt;
DateTime updatedAt;
dynamic createdBy;
dynamic updatedBy;
factory Agama.fromJson(Map<String, dynamic> json) => Agama(
id: json["id"],
idAgama: json["id_agama"],
nmAgama: json["nm_agama"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
createdBy: json["created_by"],
updatedBy: json["updated_by"],
);
Map<String, dynamic> toJson() => {
"id": id,
"id_agama": idAgama,
"nm_agama": nmAgama,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
"created_by": createdBy,
"updated_by": updatedBy,
};
}
class Jn {
Jn({
required this.id,
required this.idJnsTinggal,
required this.nmJnsTinggal,
required this.createdAt,
required this.updatedAt,
});
String id;
String idJnsTinggal;
String nmJnsTinggal;
DateTime createdAt;
DateTime updatedAt;
factory Jn.fromJson(Map<String, dynamic> json) => Jn(
id: json["id"],
idJnsTinggal: json["id_jns_tinggal"],
nmJnsTinggal: json["nm_jns_tinggal"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"id_jns_tinggal": idJnsTinggal,
"nm_jns_tinggal": nmJnsTinggal,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
class Kab {
Kab({
required this.id,
required this.idWil,
required this.nmWil,
required this.idIndukWilayah,
required this.idLevelWil,
required this.createdAt,
required this.updatedAt,
});
String id;
String idWil;
String nmWil;
String idIndukWilayah;
String idLevelWil;
DateTime createdAt;
DateTime updatedAt;
factory Kab.fromJson(Map<String, dynamic> json) => Kab(
id: json["id"],
idWil: json["id_wil"],
nmWil: json["nm_wil"],
idIndukWilayah: json["id_induk_wilayah"],
idLevelWil: json["id_level_wil"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"id_wil": idWil,
"nm_wil": nmWil,
"id_induk_wilayah": idIndukWilayah,
"id_level_wil": idLevelWil,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
class Kwn {
Kwn({
required this.id,
required this.kewarganegaraan,
required this.nmWil,
required this.createdAt,
required this.updatedAt,
});
String id;
String kewarganegaraan;
String nmWil;
DateTime createdAt;
DateTime updatedAt;
factory Kwn.fromJson(Map<String, dynamic> json) => Kwn(
id: json["id"],
kewarganegaraan: json["kewarganegaraan"],
nmWil: json["nm_wil"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"kewarganegaraan": kewarganegaraan,
"nm_wil": nmWil,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
class Pendidikan {
Pendidikan({
required this.id,
required this.idJenjDidik,
required this.nmJenjDidik,
required this.uJenjLemb,
required this.uJenjOrg,
required this.createdAt,
required this.updatedAt,
});
String id;
String idJenjDidik;
String nmJenjDidik;
int uJenjLemb;
int uJenjOrg;
DateTime createdAt;
DateTime updatedAt;
factory Pendidikan.fromJson(Map<String, dynamic> json) => Pendidikan(
id: json["id"],
idJenjDidik: json["id_jenj_didik"],
nmJenjDidik: json["nm_jenj_didik"],
uJenjLemb: json["u_jenj_lemb"],
uJenjOrg: json["u_jenj_org"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"id_jenj_didik": idJenjDidik,
"nm_jenj_didik": nmJenjDidik,
"u_jenj_lemb": uJenjLemb,
"u_jenj_org": uJenjOrg,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
class Tran {
Tran({
required this.id,
required this.idAlatTransport,
required this.nmAlatTransport,
required this.createdAt,
required this.updatedAt,
});
String id;
String idAlatTransport;
String nmAlatTransport;
DateTime createdAt;
DateTime updatedAt;
factory Tran.fromJson(Map<String, dynamic> json) => Tran(
id: json["id"],
idAlatTransport: json["id_alat_transport"],
nmAlatTransport: json["nm_alat_transport"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"id_alat_transport": idAlatTransport,
"nm_alat_transport": nmAlatTransport,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}

_TypeError (type '(dynamic) => FutureMatch' is not a subtype of type '(String, dynamic) =>

hello can anyone help me to fix this error
error coming from FutureMatch.dart
from line
List<FutureMatch> futureMatchFromJson(String str) => List<FutureMatch>.from(json.decode(str).map((x) => FutureMatch.fromJson(x)));
**Exception has occurred. _TypeError (type '(dynamic) => FutureMatch' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform')**
and my FutureMatch.dart code
`
// To parse this JSON data, do
// final futureMatch = futureMatchFromJson(jsonString);
import 'dart:convert';
List<FutureMatch> futureMatchFromJson(String str) => List<FutureMatch>.from(json.decode(str).map((x) => FutureMatch.fromJson(x)));
String futureMatchToJson(List<FutureMatch> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class FutureMatch {
FutureMatch({
this.fixture,
this.league,
this.teams,
this.goals,
this.score,
});
Fixture? fixture;
League? league;
Teams? teams;
Goals? goals;
Score? score;
factory FutureMatch.fromJson(Map<String, dynamic> json) => FutureMatch(
fixture: Fixture.fromJson(json["fixture"]),
league: League.fromJson(json["league"]),
teams:Teams.fromJson(json["teams"]),
goals: Goals.fromJson(json["goals"]),
score: Score.fromJson(json["score"]),
);
Map<String, dynamic> toJson() => {
"fixture": fixture!.toJson(),
"league": league!.toJson(),
"teams": teams!.toJson(),
"goals": goals!.toJson(),
"score": score!.toJson(),
};
}
class Teams {
Teams({
this.home,
this.away,
});
dynamic home;
dynamic away;
factory Teams.fromJson(Map<String, dynamic> json) => Teams(
home: json["home"],
away: json["away"],
);
Map<String, dynamic> toJson() => {
"home": home,
"away": away,
};
}
class Fixture {
Fixture({
this.id,
this.referee,
this.timezone,
this.date,
this.timestamp,
this.periods,
this.venue,
this.status,
});
int? id;
dynamic referee;
String? timezone;
DateTime? date;
int? timestamp;
Periods? periods;
Venue? venue;
Status? status;
factory Fixture.fromJson(Map<String, dynamic> json) => Fixture(
id: json["id"],
referee: json["referee"],
timezone: json["timezone"],
date: DateTime.parse(json["date"]),
timestamp: json["timestamp"],
periods: Periods.fromJson(json["periods"]),
venue: Venue.fromJson(json["venue"]),
status: Status.fromJson(json["status"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"referee": referee,
"timezone": timezone,
"date": date!.toIso8601String(),
"timestamp": timestamp,
"periods": periods!.toJson(),
"venue": venue!.toJson(),
"status": status!.toJson(),
};
}
class Periods {
Periods({
this.first,
this.second,
});
dynamic first;
dynamic second;
factory Periods.fromJson(Map<String, dynamic> json) => Periods(
first: json["first"],
second: json["second"],
);
Map<String, dynamic> toJson() => {
"first": first,
"second": second,
};
}
class Status {
Status({
this.long,
this.short,
this.elapsed,
});
String? long;
String? short;
dynamic elapsed;
factory Status.fromJson(Map<String, dynamic> json) => Status(
long: json["long"],
short: json["short"],
elapsed: json["elapsed"],
);
Map<String, dynamic> toJson() => {
"long": long,
"short": short,
"elapsed": elapsed,
};
}
class Venue {
Venue({
this.id,
this.name,
this.city,
});
dynamic id;
dynamic name;
dynamic city;
factory Venue.fromJson(Map<String, dynamic> json) => Venue(
id: json["id"],
name: json["name"],
city: json["city"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"city": city,
};
}
class Goals {
Goals({
this.home,
this.away,
});
int? home;
int? away;
factory Goals.fromJson(Map<String, dynamic> json) => Goals(
home: json["home"],
away: json["away"],
);
Map<String, dynamic> toJson() => {
"home": home,
"away": away,
};
}
class Away {
Away({
this.id,
this.name,
this.logo,
this.winner,
});
int? id;
String? name;
String? logo;
dynamic winner;
factory Away.fromJson(Map<String, dynamic> json) => Away(
id: json["id"],
name: json["name"],
logo: json["logo"],
winner: json["winner"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"logo": logo,
"winner": winner,
};
}
class League {
League({
this.id,
this.name,
this.country,
this.logo,
this.flag,
this.season,
this.round,
});
int? id;
String? name;
String? country;
String? logo;
String? flag;
int? season;
String? round;
factory League.fromJson(Map<String, dynamic> json) => League(
id: json["id"],
name: json["name"],
country: json["country"],
logo: json["logo"],
flag: json["flag"],
season: json["season"],
round: json["round"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"country": country,
"logo": logo,
"flag": flag,
"season": season,
"round": round,
};
}
class Score {
Score({
this.halftime,
this.fulltime,
this.extratime,
this.penalty,
});
Goals? halftime;
Goals? fulltime;
Goals? extratime;
Goals? penalty;
factory Score.fromJson(Map<String, dynamic> json) => Score(
halftime: Goals.fromJson(json["halftime"]),
fulltime: Goals.fromJson(json["fulltime"]),
extratime: Goals.fromJson(json["extratime"]),
penalty: Goals.fromJson(json["penalty"]),
);
Map<String, dynamic> toJson() => {
"halftime": halftime!.toJson(),
"fulltime": fulltime!.toJson(),
"extratime": extratime!.toJson(),
"penalty": penalty!.toJson(),
};
}
`
constent.dart
`String mainurl = "https://v3.football.api-sports.io";
String token = "###########";
`
what i can do to fix this error ?
if you need more information please write .

best practice to fetch data from api in flutter

i am working on news application (full-stack) and i am using strapi for back-end and flutter as front-end and i wondering if there is some standard or pattern to fetch data from api in flutter (or any front-end )
cuz there are many methods can be used but i am asking for best approach ,
for example i can fetch list of data with it's related entities to the front end ( with http://localhost:1337/api/news-items?populate=*
but the problem with this approach is
if any related entity is null an exception occurred [thank for
null-safety ]
the model or dto become very complex that leads to get god class
class NewsItemList {
NewsItemList({
required this.data,
required this.meta,
});
List<NewsItemListDatum> data;
Meta meta;
factory NewsItemList.fromJson(Map<String, dynamic> json) => NewsItemList(
data: List<NewsItemListDatum>.from(json["data"].map((x) => NewsItemListDatum.fromJson(x))),
meta: Meta.fromJson(json["meta"]),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"meta": meta.toJson(),
};
}
class NewsItemListDatum {
NewsItemListDatum({
required this.id,
required this.attributes,
});
int id;
PurpleAttributes attributes;
factory NewsItemListDatum.fromJson(Map<String, dynamic> json) => NewsItemListDatum(
id: json["id"],
attributes: PurpleAttributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"attributes": attributes.toJson(),
};
}
class PurpleAttributes {
PurpleAttributes({
required this.title,
required this.description,
required this.pubDate,
required this.author,
required this.createdAt,
required this.updatedAt,
required this.content,
required this.link,
required this.source,
required this.thumbnail,
required this.newsCats,
required this.comments,
required this.governorate,
required this.likes,
});
String title;
String description;
String pubDate;
String author;
DateTime createdAt;
DateTime updatedAt;
String content;
String link;
String source;
String thumbnail;
NewsCats newsCats;
Comments comments;
Governorate governorate;
Likes likes;
factory PurpleAttributes.fromJson(Map<String, dynamic> json) => PurpleAttributes(
title: json["title"],
description: json["description"],
pubDate: json["pubDate"],
author: json["author"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
content: json["content"],
link: json["link"],
source: json["source"],
thumbnail: json["thumbnail"],
newsCats: NewsCats.fromJson(json["news_cats"]),
comments: Comments.fromJson(json["comments"]),
governorate: Governorate.fromJson(json["governorate"]),
likes: Likes.fromJson(json["likes"]),
);
Map<String, dynamic> toJson() => {
"title": title,
"description": description,
"pubDate": pubDate,
"author": author,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
"content": content,
"link": link,
"source": source,
"thumbnail": thumbnail,
"news_cats": newsCats.toJson(),
"comments": comments.toJson(),
"governorate": governorate.toJson(),
"likes": likes.toJson(),
};
}
class Comments {
Comments({
required this.data,
});
List<CommentsDatum> data;
factory Comments.fromJson(Map<String, dynamic> json) => Comments(
data: List<CommentsDatum>.from(json["data"].map((x) => CommentsDatum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class CommentsDatum {
CommentsDatum({
required this.id,
required this.attributes,
});
int id;
FluffyAttributes attributes;
factory CommentsDatum.fromJson(Map<String, dynamic> json) => CommentsDatum(
id: json["id"],
attributes: FluffyAttributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"attributes": attributes.toJson(),
};
}
class FluffyAttributes {
FluffyAttributes({
required this.content,
required this.createdAt,
required this.updatedAt,
});
String content;
DateTime createdAt;
DateTime updatedAt;
factory FluffyAttributes.fromJson(Map<String, dynamic> json) => FluffyAttributes(
content: json["content"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
);
Map<String, dynamic> toJson() => {
"content": content,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
};
}
class Governorate {
Governorate({
required this.data,
});
Dat data;
factory Governorate.fromJson(Map<String, dynamic> json) => Governorate(
data: Dat.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"data": data.toJson(),
};
}
class Dat {
Dat({
required this.id,
required this.attributes,
});
int id;
DataAttributes attributes;
factory Dat.fromJson(Map<String, dynamic> json) => Dat(
id: json["id"],
attributes: DataAttributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"attributes": attributes.toJson(),
};
}
class DataAttributes {
DataAttributes({
required this.name,
required this.createdAt,
required this.updatedAt,
});
String name;
DateTime createdAt;
DateTime updatedAt;
factory DataAttributes.fromJson(Map<String, dynamic> json) => DataAttributes(
name: json["name"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
);
Map<String, dynamic> toJson() => {
"name": name,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
};
}
class Likes {
Likes({
required this.data,
});
List<LikesDatum> data;
factory Likes.fromJson(Map<String, dynamic> json) => Likes(
data: List<LikesDatum>.from(json["data"].map((x) => LikesDatum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class LikesDatum {
LikesDatum({
required this.id,
required this.attributes,
});
int id;
TentacledAttributes attributes;
factory LikesDatum.fromJson(Map<String, dynamic> json) => LikesDatum(
id: json["id"],
attributes: TentacledAttributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"attributes": attributes.toJson(),
};
}
class TentacledAttributes {
TentacledAttributes({
required this.likeit,
required this.createdAt,
required this.updatedAt,
required this.publishedAt,
});
bool likeit;
DateTime createdAt;
DateTime updatedAt;
DateTime publishedAt;
factory TentacledAttributes.fromJson(Map<String, dynamic> json) => TentacledAttributes(
likeit: json["likeit"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
publishedAt: DateTime.parse(json["publishedAt"]),
);
Map<String, dynamic> toJson() => {
"likeit": likeit,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
"publishedAt": publishedAt.toIso8601String(),
};
}
class NewsCats {
NewsCats({
required this.data,
});
List<Dat> data;
factory NewsCats.fromJson(Map<String, dynamic> json) => NewsCats(
data: List<Dat>.from(json["data"].map((x) => Dat.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Meta {
Meta({
required this.pagination,
});
Pagination pagination;
factory Meta.fromJson(Map<String, dynamic> json) => Meta(
pagination: Pagination.fromJson(json["pagination"]),
);
Map<String, dynamic> toJson() => {
"pagination": pagination.toJson(),
};
}
class Pagination {
Pagination({
required this.page,
required this.pageSize,
required this.pageCount,
required this.total,
});
int page;
int pageSize;
int pageCount;
int total;
factory Pagination.fromJson(Map<String, dynamic> json) => Pagination(
page: json["page"],
pageSize: json["pageSize"],
pageCount: json["pageCount"],
total: json["total"],
);
Map<String, dynamic> toJson() => {
"page": page,
"pageSize": pageSize,
"pageCount": pageCount,
"total": total,
};
}
the code generated using https://app.quicktype.io/
3- delay occurred cuz of transection in the backend and amount of data handled in application
4- although it is hard coded but it is useful cuz i don't need to make a lot of api calls [ like get comments where item id is 5 ]
or i can fetch a list of data without it's related entities
in this case i will get list of items and every time i need get related entity i make another api call
class NewsItemsListApiData {
NewsItemsListApiData({
required this.data,
required this.meta,
});
List<NewsItem> data;
Meta meta;
factory NewsItemsListApiData.fromJson(Map<String, dynamic> json) =>
NewsItemsListApiData(
data:
List<NewsItem>.from(json["data"].map((x) => NewsItem.fromJson(x))),
meta: Meta.fromJson(json["meta"]),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"meta": meta.toJson(),
};
}
class NewsItem {
NewsItem({
required this.id,
required this.attributes,
});
int id;
Attributes attributes;
factory NewsItem.fromJson(Map<String, dynamic> json) => NewsItem(
id: json["id"],
attributes: Attributes.fromJson(json["attributes"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"attributes": attributes.toJson(),
};
}
class Attributes {
Attributes({
required this.title,
required this.description,
required this.pubDate,
required this.author,
required this.createdAt,
required this.updatedAt,
required this.content,
required this.link,
required this.source,
required this.thumbnail,
});
String title;
String description;
String pubDate;
String author;
DateTime createdAt;
DateTime updatedAt;
String content;
String link;
String source;
String thumbnail;
factory Attributes.fromJson(Map<String, dynamic> json) => Attributes(
title: json["title"],
description: json["description"],
pubDate: json["pubDate"],
author: json["author"],
createdAt: DateTime.parse(json["createdAt"]),
updatedAt: DateTime.parse(json["updatedAt"]),
content: json["content"],
link: json["link"],
source: json["source"],
thumbnail: json["thumbnail"],
);
Map<String, dynamic> toJson() => {
"title": title,
"description": description,
"pubDate": pubDate,
"author": author,
"createdAt": createdAt.toIso8601String(),
"updatedAt": updatedAt.toIso8601String(),
"content": content,
"link": link,
"source": source,
"thumbnail": thumbnail,
};
}
class Meta {
Meta({
required this.pagination,
});
Pagination pagination;
factory Meta.fromJson(Map<String, dynamic> json) => Meta(
pagination: Pagination.fromJson(json["pagination"]),
);
Map<String, dynamic> toJson() => {
"pagination": pagination.toJson(),
};
}
class Pagination {
Pagination({
required this.page,
required this.pageSize,
required this.pageCount,
required this.total,
});
int page;
int pageSize;
int pageCount;
int total;
factory Pagination.fromJson(Map<String, dynamic> json) => Pagination(
page: json["page"],
pageSize: json["pageSize"],
pageCount: json["pageCount"],
total: json["total"],
);
Map<String, dynamic> toJson() => {
"page": page,
"pageSize": pageSize,
"pageCount": pageCount,
"total": total,
};
}
so any ideas about best practice and clean code or any other methods makes the code less error prone and more clean ?

I got an error while getting data from the API, how should I get the data if flutter?

I am getting data from an API using a model. But I ran into a problem that when I get the 'gallery' data, I get an error, that is, I get the data incorrectly. I need to get the 'gallery' field and inside it take the 'url' field - a link to the photo, in order to use it in the future. Can you tell me how to get the 'url' field correctly?
{
"data": {
"id": 35,
"picture_url": null,
"email_confirmed": false,
"gallery": [
{
"url": "https://picture-staging.s3.eu-central.jpeg",
"mime_type": "image/jpeg",
"type": "gallery",
"updated_at": "2022",
"created_at": "2022"
}
],
"updated_at": "2022",
"created_at": "2022"
}
}
model
class User {
final int id;
List? gallery;
User({
required this.id,
this.gallery,
});
User.fromJson(Map<String, dynamic> json)
: this(
id: json['id'] as int,
gallery: json['gallery']['url'],
);
In your API response, there is a list of gallery objects therefore you have to traverse through all of them.
User.fromJson(Map<String, dynamic> json) {
json = json['data'];
id = json['id'];
pictureUrl = json['picture_url'];
emailConfirmed = json['email_confirmed'];
if (json['gallery'] != null) {
gallery = <Gallery>[];
json['gallery'].forEach((v) {
gallery!.add(new Gallery.fromJson(v));
});
}
updatedAt = json['updated_at'];
createdAt = json['created_at'];
}
There are multiple tools that helps you create that .fromJson method, like this. Paste your json there and it will generate dart code for you, really helps me.
The usage should like this:
User user = User.fromJson(yourApiResponseJson);
print(user.id);
print(user.gallery); //prints entire list of gallery
print(user.gallery.first.url); //prints only first object url
I hope that is not your whole model, because that model is not accessing the "data" key on the json response, your model should start getting the key data then pass it to another class that in this case should be named User
here is a brief example
class User {
User({
required this.data,
});
final Data data;
factory User.fromJson(Map<String, dynamic> json) => User(
data: Data.fromJson(json["data"]),
);
}
The Data class could be like this:
class Data {
Data({
required this.id,
required this.pictureUrl,
required this.emailConfirmed,
required this.gallery,
required this.updatedAt,
required this.createdAt,
});
final int id;
final dynamic pictureUrl;
final bool emailConfirmed;
final List<Gallery> gallery;
final String updatedAt;
final String createdAt;
factory Data.fromJson(Map<String, dynamic> json) => Data(
id: json["id"],
pictureUrl: json["picture_url"],
emailConfirmed: json["email_confirmed"],
gallery: List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
updatedAt: json["updated_at"],
createdAt: json["created_at"],
);
}
I reccomend you using Quicktype
Hey you can use this tool to generate your dart model from json.
Below is generated code from above tool
// final user = userFromJson(jsonString);
import 'dart:convert';
User userFromJson(String str) => User.fromJson(json.decode(str));
String userToJson(User data) => json.encode(data.toJson());
class User {
User({
required this.data,
});
Data data;
factory User.fromJson(Map<String, dynamic> json) => User(
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"data": data.toJson(),
};
}
class Data {
Data({
this.id,
this.pictureUrl,
this.emailConfirmed,
this.gallery,
this.updatedAt,
this.createdAt,
});
int? id;
String? pictureUrl;
bool? emailConfirmed;
List<Gallery>? gallery;
String? updatedAt;
String? createdAt;
factory Data.fromJson(Map<String, dynamic> json) => Data(
id: json["id"],
pictureUrl: json["picture_url"],
emailConfirmed: json["email_confirmed"],
gallery: List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
updatedAt: json["updated_at"],
createdAt: json["created_at"],
);
Map<String, dynamic> toJson() => {
"id": id,
"picture_url": pictureUrl,
"email_confirmed": emailConfirmed,
"gallery": List<dynamic>.from(gallery.map((x) => x.toJson())),
"updated_at": updatedAt,
"created_at": createdAt,
};
}
class Gallery {
Gallery({
this.url,
this.mimeType,
this.type,
this.updatedAt,
this.createdAt,
});
String? url;
String? mimeType;
String? type;
String? updatedAt;
String? createdAt;
factory Gallery.fromJson(Map<String, dynamic> json) => Gallery(
url: json["url"],
mimeType: json["mime_type"],
type: json["type"],
updatedAt: json["updated_at"],
createdAt: json["created_at"],
);
Map<String, dynamic> toJson() => {
"url": url,
"mime_type": mimeType,
"type": type,
"updated_at": updatedAt,
"created_at": createdAt,
};
}
// You can use like this
final user = userFromJson(jsonString);
String? url = user.data?.gallery?.url;

Flutter _TypeError (type 'Null' is not a subtype of type 'Map<String, dynamic>')

I am facing an issue with my app, I want to use the WordPress rest API in my flutter application. The problem is when I am trying to Access the UserData model using the CourseData model I am getting an error like that. I want to access the userdata through the course data so that I can get the author's name and details also.
Course Data Model
List<CourseData> courseDataFromJson(String str) =>
List<CourseData>.from(json.decode(str).map((x) => CourseData.fromJson(x)));
String courseDataToJson(List<CourseData> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class CourseData {
CourseData({
required this.id,
required this.date,
required this.dateGmt,
required this.guid,
required this.modified,
required this.modifiedGmt,
required this.slug,
required this.status,
required this.type,
required this.link,
required this.title,
required this.content,
required this.excerpt,
required this.author,
required this.featuredMedia,
required this.template,
required this.courseCategory,
required this.courseTag,
required this.links,
required this.authordata,
});
int id;
DateTime date;
DateTime dateGmt;
Guid guid;
DateTime modified;
DateTime modifiedGmt;
String slug;
String status;
String type;
String link;
Guid title;
Content content;
Content excerpt;
int author;
int featuredMedia;
String template;
List<int> courseCategory;
List<int> courseTag;
Links links;
UsersData authordata;
factory CourseData.fromJson(Map<String, dynamic> json) => CourseData(
id: json["id"],
date: DateTime.parse(json["date"]),
dateGmt: DateTime.parse(json["date_gmt"]),
guid: Guid.fromJson(json["guid"]),
modified: DateTime.parse(json["modified"]),
modifiedGmt: DateTime.parse(json["modified_gmt"]),
slug: json["slug"],
status: json["status"],
type: json["type"],
link: json["link"],
title: Guid.fromJson(json["title"]),
content: Content.fromJson(json["content"]),
excerpt: Content.fromJson(json["excerpt"]),
author: json["author"],
featuredMedia: json["featured_media"],
template: json["template"],
courseCategory: List<int>.from(json["course-category"].map((x) => x)),
courseTag: List<int>.from(json["course-tag"].map((x) => x)),
links: Links.fromJson(json["_links"]),
authordata: UsersData.fromJson(json["authordata"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"date": date.toIso8601String(),
"date_gmt": dateGmt.toIso8601String(),
"guid": guid.toJson(),
"modified": modified.toIso8601String(),
"modified_gmt": modifiedGmt.toIso8601String(),
"slug": slug,
"status": status,
"type": type,
"link": link,
"title": title.toJson(),
"content": content.toJson(),
"excerpt": excerpt.toJson(),
"author": author,
"featured_media": featuredMedia,
"template": template,
"course-category": List<dynamic>.from(courseCategory.map((x) => x)),
"course-tag": List<dynamic>.from(courseTag.map((x) => x)),
"_links": links.toJson(),
"authordata": authordata.toJson(),
};
}
class Content {
Content({
required this.rendered,
required this.protected,
});
String rendered;
bool protected;
factory Content.fromJson(Map<String, dynamic> json) => Content(
rendered: json["rendered"],
protected: json["protected"],
);
Map<String, dynamic> toJson() => {
"rendered": rendered,
"protected": protected,
};
}
class Guid {
Guid({
required this.rendered,
});
String rendered;
factory Guid.fromJson(Map<String, dynamic> json) => Guid(
rendered: json["rendered"],
);
Map<String, dynamic> toJson() => {
"rendered": rendered,
};
}
class Links {
Links({
required this.self,
required this.collection,
required this.about,
required this.author,
required this.wpFeaturedmedia,
required this.wpAttachment,
required this.wpTerm,
required this.curies,
});
List<About> self;
List<About> collection;
List<About> about;
List<Author> author;
List<Author> wpFeaturedmedia;
List<About> wpAttachment;
List<WpTerm> wpTerm;
List<Cury> curies;
factory Links.fromJson(Map<String, dynamic> json) => Links(
self: List<About>.from(json["self"].map((x) => About.fromJson(x))),
collection:
List<About>.from(json["collection"].map((x) => About.fromJson(x))),
about: List<About>.from(json["about"].map((x) => About.fromJson(x))),
author:
List<Author>.from(json["author"].map((x) => Author.fromJson(x))),
wpFeaturedmedia: List<Author>.from(
json["wp:featuredmedia"].map((x) => Author.fromJson(x))),
wpAttachment: List<About>.from(
json["wp:attachment"].map((x) => About.fromJson(x))),
wpTerm:
List<WpTerm>.from(json["wp:term"].map((x) => WpTerm.fromJson(x))),
curies: List<Cury>.from(json["curies"].map((x) => Cury.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"self": List<dynamic>.from(self.map((x) => x.toJson())),
"collection": List<dynamic>.from(collection.map((x) => x.toJson())),
"about": List<dynamic>.from(about.map((x) => x.toJson())),
"author": List<dynamic>.from(author.map((x) => x.toJson())),
"wp:featuredmedia":
List<dynamic>.from(wpFeaturedmedia.map((x) => x.toJson())),
"wp:attachment":
List<dynamic>.from(wpAttachment.map((x) => x.toJson())),
"wp:term": List<dynamic>.from(wpTerm.map((x) => x.toJson())),
"curies": List<dynamic>.from(curies.map((x) => x.toJson())),
};
}
class About {
About({
required this.href,
});
String href;
factory About.fromJson(Map<String, dynamic> json) => About(
href: json["href"],
);
Map<String, dynamic> toJson() => {
"href": href,
};
}
class Author {
Author({
required this.embeddable,
required this.href,
});
bool embeddable;
String href;
factory Author.fromJson(Map<String, dynamic> json) => Author(
embeddable: json["embeddable"],
href: json["href"],
);
Map<String, dynamic> toJson() => {
"embeddable": embeddable,
"href": href,
};
}
class Cury {
Cury({
required this.name,
required this.href,
required this.templated,
});
String name;
String href;
bool templated;
factory Cury.fromJson(Map<String, dynamic> json) => Cury(
name: json["name"],
href: json["href"],
templated: json["templated"],
);
Map<String, dynamic> toJson() => {
"name": name,
"href": href,
"templated": templated,
};
}
class WpTerm {
WpTerm({
required this.taxonomy,
required this.embeddable,
required this.href,
});
String taxonomy;
bool embeddable;
String href;
factory WpTerm.fromJson(Map<String, dynamic> json) => WpTerm(
taxonomy: json["taxonomy"],
embeddable: json["embeddable"],
href: json["href"],
);
Map<String, dynamic> toJson() => {
"taxonomy": taxonomy,
"embeddable": embeddable,
"href": href,
};
}
User Data Model
List<UsersData> usersDataFromJson(String str) =>
List<UsersData>.from(json.decode(str).map((x) => UsersData.fromJson(x)));
String usersDataToJson(List<UsersData> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class UsersData {
UsersData({
required this.id,
required this.name,
required this.url,
required this.description,
required this.link,
required this.slug,
required this.avatarUrls,
required this.meta,
required this.isSuperAdmin,
required this.woocommerceMeta,
required this.links,
});
int id;
String name;
String url;
String description;
String link;
String slug;
Map<String, String> avatarUrls;
List<dynamic> meta;
bool isSuperAdmin;
WoocommerceMeta woocommerceMeta;
Links links;
factory UsersData.fromJson(Map<String, dynamic> json) => UsersData(
id: json["id"],
name: json["name"],
url: json["url"],
description: json["description"],
link: json["link"],
slug: json["slug"],
avatarUrls: Map.from(json["avatar_urls"])
.map((k, v) => MapEntry<String, String>(k, v)),
meta: List<dynamic>.from(json["meta"].map((x) => x)),
isSuperAdmin: json["is_super_admin"],
woocommerceMeta: WoocommerceMeta.fromJson(json["woocommerce_meta"]),
links: Links.fromJson(json["_links"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"url": url,
"description": description,
"link": link,
"slug": slug,
"avatar_urls":
Map.from(avatarUrls).map((k, v) => MapEntry<String, dynamic>(k, v)),
"meta": List<dynamic>.from(meta.map((x) => x)),
"is_super_admin": isSuperAdmin,
"woocommerce_meta": woocommerceMeta.toJson(),
"_links": links.toJson(),
};
}
class Links {
Links({
required this.self,
required this.collection,
});
List<Collection> self;
List<Collection> collection;
factory Links.fromJson(Map<String, dynamic> json) => Links(
self: List<Collection>.from(
json["self"].map((x) => Collection.fromJson(x))),
collection: List<Collection>.from(
json["collection"].map((x) => Collection.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"self": List<dynamic>.from(self.map((x) => x.toJson())),
"collection": List<dynamic>.from(collection.map((x) => x.toJson())),
};
}
class Collection {
Collection({
required this.href,
});
String href;
factory Collection.fromJson(Map<String, dynamic> json) => Collection(
href: json["href"],
);
Map<String, dynamic> toJson() => {
"href": href,
};
}
class WoocommerceMeta {
WoocommerceMeta({
required this.activityPanelInboxLastRead,
required this.activityPanelReviewsLastRead,
required this.categoriesReportColumns,
required this.couponsReportColumns,
required this.customersReportColumns,
required this.ordersReportColumns,
required this.productsReportColumns,
required this.revenueReportColumns,
required this.taxesReportColumns,
required this.variationsReportColumns,
required this.dashboardSections,
required this.dashboardChartType,
required this.dashboardChartInterval,
required this.dashboardLeaderboardRows,
required this.homepageLayout,
required this.homepageStats,
required this.taskListTrackedStartedTasks,
required this.helpPanelHighlightShown,
required this.androidAppBannerDismissed,
});
String activityPanelInboxLastRead;
String activityPanelReviewsLastRead;
String categoriesReportColumns;
String couponsReportColumns;
String customersReportColumns;
String ordersReportColumns;
String productsReportColumns;
String revenueReportColumns;
String taxesReportColumns;
String variationsReportColumns;
String dashboardSections;
String dashboardChartType;
String dashboardChartInterval;
String dashboardLeaderboardRows;
String homepageLayout;
String homepageStats;
String taskListTrackedStartedTasks;
String helpPanelHighlightShown;
String androidAppBannerDismissed;
factory WoocommerceMeta.fromJson(Map<String, dynamic> json) =>
WoocommerceMeta(
activityPanelInboxLastRead: json["activity_panel_inbox_last_read"],
activityPanelReviewsLastRead: json["activity_panel_reviews_last_read"],
categoriesReportColumns: json["categories_report_columns"],
couponsReportColumns: json["coupons_report_columns"],
customersReportColumns: json["customers_report_columns"],
ordersReportColumns: json["orders_report_columns"],
productsReportColumns: json["products_report_columns"],
revenueReportColumns: json["revenue_report_columns"],
taxesReportColumns: json["taxes_report_columns"],
variationsReportColumns: json["variations_report_columns"],
dashboardSections: json["dashboard_sections"],
dashboardChartType: json["dashboard_chart_type"],
dashboardChartInterval: json["dashboard_chart_interval"],
dashboardLeaderboardRows: json["dashboard_leaderboard_rows"],
homepageLayout: json["homepage_layout"],
homepageStats: json["homepage_stats"],
taskListTrackedStartedTasks: json["task_list_tracked_started_tasks"],
helpPanelHighlightShown: json["help_panel_highlight_shown"],
androidAppBannerDismissed: json["android_app_banner_dismissed"],
);
Map<String, dynamic> toJson() => {
"activity_panel_inbox_last_read": activityPanelInboxLastRead,
"activity_panel_reviews_last_read": activityPanelReviewsLastRead,
"categories_report_columns": categoriesReportColumns,
"coupons_report_columns": couponsReportColumns,
"customers_report_columns": customersReportColumns,
"orders_report_columns": ordersReportColumns,
"products_report_columns": productsReportColumns,
"revenue_report_columns": revenueReportColumns,
"taxes_report_columns": taxesReportColumns,
"variations_report_columns": variationsReportColumns,
"dashboard_sections": dashboardSections,
"dashboard_chart_type": dashboardChartType,
"dashboard_chart_interval": dashboardChartInterval,
"dashboard_leaderboard_rows": dashboardLeaderboardRows,
"homepage_layout": homepageLayout,
"homepage_stats": homepageStats,
"task_list_tracked_started_tasks": taskListTrackedStartedTasks,
"help_panel_highlight_shown": helpPanelHighlightShown,
"android_app_banner_dismissed": androidAppBannerDismissed,
};
}
Any Help will be appreciated.
Checking the url https://egiye.com/wp-json/wp/v2/courses (shared in comment) I don't see any authordata prop, so that is why flutter is telling you that it is expecting a map but it receives a null value instead.