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(),
};
}
I have the following code in my flutter app:
MODELS:
APIUser apiUserFromJson(String str) => APIUser.fromJson(json.decode(str));
String apiUserToJson(APIUser data) => json.encode(data.toJson());
class APIUser {
APIUser({this.id, this.username, this.email, this.role});
int? id;
String? username;
int? email;
String? role;
factory APIUser.fromJson(Map<String, dynamic> json) => APIUser(
id: json["user"]["id"],
username: json["user"]["username"],
email: json["user"]["email"],
role: json["user_role"],
);
Map<String, dynamic> toJson() => {
"id": id,
"username": username,
"email": email,
"role": role,
};
}
GlobalUser globalUsersFromJson(String str) =>
GlobalUser.fromJson(json.decode(str));
String globalUsersToJson(GlobalUser data) => json.encode(data.toJson());
class GlobalUser {
GlobalUser({
this.users,
});
List<APIUser>? users;
factory GlobalUser.fromJson(Map<String, dynamic> json) => GlobalUser(
users:
List<APIUser>.from(json["users"].map((x) => APIUser.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"users": List<dynamic>.from(users!.map((x) => x.toJson())),
};
}
UPDATED
MY METHOD FOR FETCHING:
Future<dynamic> getGlobalUsers() async {
try {
var token = storage.read('token');
final uri = Uri.parse("${ApiConstants.baseUrl}/get_users");
final headers = {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Token $token'
};
var response = await http.post(uri,
headers: headers); // Request Timeout response status code
**print(response);**
if (response.statusCode == 200) {
GlobalUser globalUsers = globalUsersFromJson(response.body);
return globalUsers;
}
if (response.statusCode == 401) {
return http.Response('Error', 401);
}
if (response.statusCode >= 500) {
return http.Response('Error', 500);
}
} catch (e) {
log(e.toString());
}
}
API RESPONSE IN POSTMAN FOR THE URL ASKED IN PREVIOUS METHOD getGlobalUsers:
[
{
"user": {
"id": 16,
"last_login": "2022-11-27T16:20:42.271178+01:00",
"username": "user1",
"email": "user1#mail.es",
"date_joined": "2022-11-27T15:30:47.851322+01:00",
"groups": [],
"user_permissions": []
},
"user_role": "worker"
}
]
In flutter, if I print the response of this method, I´m getting [], and I´m not sure about what am I doing wrong. The whole Backend API is working OK , as in POSTMan. THE PRINT STATEMENT IN FETCHING METHOD RETURNS NOTHING
Thanks in advance
int? email should be a String? email
You need to return List<dynamic> as your API response data is List
GlobalUser globalUsersFromJson(String str) =>
GlobalUser.fromJson(json.decode(str)as List<dynamic>);
factory GlobalUser.fromJson(List<dynamic> json) => GlobalUser(
users:
json
.map((e) => APIUser.fromJson(e as Map<String, dynamic>))
.toList();
);
TRY THIS...
factory GlobalUser.fromJson(Map<String, dynamic> json) => GlobalUser(
users:
List<APIUser>.from(json.map((x) => APIUser.fromJson(x))),
);
what you are doing is fetching all the data from the API and then using the data that you want in the widget in your app.
hello permission to ask I'm trying to get the API to then display and the response is 200 ok. but when I try to display it on the screen the following error occurs
this is a function to get data from API
Future<Datum> getPaketKuliah() async {
String url = Constant.baseURL;
String token = await UtilSharedPreferences.getToken();
final response = await http.get(
Uri.parse(
'$url/auth/mhs_siakad/perwalian/get_paket',
),
headers: {
'Authorization': 'Bearer $token',
},
);
print(response.statusCode);
print(response.body);
if (response.statusCode == 200) {
return Datum.fromJson(jsonDecode(response.body));
} else {
throw Exception();
}
}
and I want to display it on the page using FutureBuilder
Container(
child: FutureBuilder<Datum>(
future: AuthProvider().getPaketKuliah(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.kelas);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
and lastly this is the model class I want to take to display on the
page
// To parse this JSON data, do
//
// final getPaket = getPaketFromJson(jsonString);
import 'dart:convert';
GetPaket getPaketFromJson(String str) => GetPaket.fromJson(json.decode(str));
String getPaketToJson(GetPaket data) => json.encode(data.toJson());
class GetPaket {
GetPaket({
required this.status,
required this.code,
required this.data,
});
String status;
String code;
Map<String, Datum> data;
factory GetPaket.fromJson(Map<String, dynamic> json) => GetPaket(
status: json["status"],
code: json["code"],
data: Map.from(json["data"])
.map((k, v) => MapEntry<String, Datum>(k, Datum.fromJson(v))),
);
Map<String, dynamic> toJson() => {
"status": status,
"code": code,
"data": Map.from(data)
.map((k, v) => MapEntry<String, dynamic>(k, v.toJson())),
};
}
class Datum {
Datum({
this.id,
this.idDosen,
this.idMk,
required this.nidn,
this.dosen,
this.idKelasKuliah,
this.kelasKuliah,
this.prodi,
this.kelas,
this.semester,
this.kelompokKelas,
required this.kode,
this.sks,
this.jumlahKelas,
this.matakuliah,
this.smt,
this.bobotSks,
this.rencanaPertemuan,
this.jenisEvaluasi,
required this.createdAt,
required this.updatedAt,
this.createdBy,
this.updatedBy,
});
String? id;
String? idDosen;
String? idMk;
dynamic nidn;
String? dosen;
String? idKelasKuliah;
String? kelasKuliah;
String? prodi;
String? kelas;
String? semester;
String? kelompokKelas;
dynamic kode;
int? sks;
int? jumlahKelas;
String? matakuliah;
String? smt;
int? bobotSks;
int? rencanaPertemuan;
String? jenisEvaluasi;
DateTime createdAt;
DateTime updatedAt;
String? createdBy;
String? updatedBy;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
idDosen: json["id_dosen"],
idMk: json["id_mk"],
nidn: json["nidn"],
dosen: json["dosen"],
idKelasKuliah: json["id_kelas_kuliah"],
kelasKuliah: json["kelas_kuliah"],
prodi: json["prodi"],
kelas: json["kelas"],
semester: json["semester"],
kelompokKelas: json["kelompok_kelas"],
kode: json["kode"],
sks: json["sks"],
jumlahKelas: json["jumlah_kelas"],
matakuliah: json["matakuliah"],
smt: json["smt"],
bobotSks: json["bobot_sks"],
rencanaPertemuan: json["rencana_pertemuan"],
jenisEvaluasi: json["jenis_evaluasi"],
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_dosen": idDosen,
"id_mk": idMk,
"nidn": nidn,
"dosen": dosen,
"id_kelas_kuliah": idKelasKuliah,
"kelas_kuliah": kelasKuliah,
"prodi": prodi,
"kelas": kelas,
"semester": semester,
"kelompok_kelas": kelompokKelas,
"kode": kode,
"sks": sks,
"jumlah_kelas": jumlahKelas,
"matakuliah": matakuliah,
"smt": smt,
"bobot_sks": bobotSks,
"rencana_pertemuan": rencanaPertemuan,
"jenis_evaluasi": jenisEvaluasi,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
"created_by": createdBy,
"updated_by": updatedBy,
};
}
and this is the json response
I highly recommend using library like json_serilizable to generate factory fromJson
factory Paket.romJson(Map<String, dynamic> json) => Paket(
status: json['status'] as String,
code: json['code'] as String,
data: (json['data'] as Map<String, dynamic>).map(
(k, e) => MapEntry(k, Datum.fromJson(e as Map<String, dynamic>)),
),
);
As provided api response corresponds to GetPaket class not Datum class you need to change getPaketKuliah method to
Future<Datum> getPaketKuliah() async {
String url = Constant.baseURL;
String token = await UtilSharedPreferences.getToken();
final response = await http.get(
Uri.parse(
'$url/auth/mhs_siakad/perwalian/get_paket',
),
headers: {
'Authorization': 'Bearer $token',
},
);
print(response.statusCode);
print(response.body);
if (response.statusCode == 200) {
// --return Datum.fromJson(jsonDecode(response.body));
final paket = GetPaket.fromJson(jsonDecode(response.body));
// -- return Datum.fromJson(paket.data.entries.first.value);
return paket.data.entries.first.value;
} else {
throw Exception();
}
}
I'm trying to Integrate the API using model. Let say I have a book screen, so I'm trying to get its API data using model. my model looks like this.
class Book {
final int id;
final String phone;
final String name;
final String relation;
final String updated_at;
final String created_at;
final int userId;
Book(
{required this.id,
required this.name,
required this.phone,
required this.relation,
required this.created_at,
// required this.image,
required this.updated_at,
required this.userId,
});
factory Book.fromJson(Map<String, dynamic> json) => Book(
id: json['user_id'],
name: json['contact_person'],
relation: json['relation'],
phone: json['phone'],
updated_at: json['updated_at'],
created_at: json['created_at'],
userId: json['id']
);
Map<String, dynamic> toJson() => {
'user_id': userId,
'contact_person': phone,
'relation': relation,
'name': name,
'created_at':created_at,
'updated_at':updated_at,
'id':id,
};
}
calling this api like this
Future<List<Book>> getBook() async {
List<Book> _bookList =[];
Map<String, String> headers = {
"Content-type": "application/json",
'Authorization': 'Bearer $token',
};
var url = Uri.parse(ApiPath.getAllEmergenceyContactUrl);
final response = await http.get(url, headers: headers);
if (response.statusCode == 200) {
Map<String, dynamic> map = json.decode(response.body);
List<dynamic> data = map["user"];
if(data.length>0){
for(int i=0;i<data.length;i++){
if(data[i]!=null){
Map<String,dynamic> map=data[i];
_bookList.add(Book.fromJson(map));
debugPrint('Id-------${map['contact_person']}'); //this print the correct data
}
}
}
print(_bookList);
return _bookList;
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
print(_bookList); this give me this output
[Instance of 'Book', Instance of 'Book']
and calling in User Interface like this
List<Book> books = [];
getAllEmergenceyContacts()async{
var books = await services.getBook();
}
i can't able to get the the when using the books in listview builder, please help me out.
my json data look like this
{
"status": 1,
"message": "your emergency contacts",
"user": [
{
"id": 10,
"user_id": 49,
"contact_person": "ABC",
"relation": "DSVKJDSB",
"phone": "sdfsdf",
"image": "emergency/1735686398652391.png",
"created_at": "2022-06-15T07:52:19.000000Z",
"updated_at": "2022-06-15T07:52:19.000000Z"
},
]}
and i want user array data from it.
I optimized your code and fix your problem. You can try it and tell me if have any problem
Model
import 'dart:convert';
Book bookFromJson(String str) => Book.fromJson(json.decode(str));
String bookToJson(Book data) => json.encode(data.toJson());
class Book {
Book({
this.status,
this.message,
this.user,
});
int status;
String message;
List<User> user;
factory Book.fromJson(Map<String, dynamic> json) => Book(
status: json["status"],
message: json["message"],
user: List<User>.from(json["user"].map((x) => User.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"message": message,
"user": List<dynamic>.from(user.map((x) => x.toJson())),
};
}
class User {
User({
this.id,
this.userId,
this.contactPerson,
this.relation,
this.phone,
this.image,
this.createdAt,
this.updatedAt,
});
int id;
int userId;
String contactPerson;
String relation;
String phone;
String image;
DateTime createdAt;
DateTime updatedAt;
factory User.fromJson(Map<String, dynamic> json) => User(
id: json["id"],
userId: json["user_id"],
contactPerson: json["contact_person"],
relation: json["relation"],
phone: json["phone"],
image: json["image"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"user_id": userId,
"contact_person": contactPerson,
"relation": relation,
"phone": phone,
"image": image,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
Call API
Future getBook() async {
Map<String, String> headers = {
"Content-type": "application/json",
'Authorization': 'Bearer $token',
};
var url = Uri.parse(ApiPath.getAllEmergenceyContactUrl);
final response = await http.get(url, headers: headers);
if (response.statusCode == 200) {
return bookFromJson(response.body).user;
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
Calling in ui screen
List<Book> books = [];
getAllEmergenceyContacts()async{
books = await services.getBook();
setState((){});
}
Listview builder
ListView.builder(
itemCount: books.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(books[index].name),
);
},
),
print(_bookList); this gives you this output [Instance of 'Book', Instance of 'Book'] because you try to print every Book class instance
You declare List<Book> _bookList =[]; , where _bookList holds Book Class as a child.
At first, Fetch the books from API
List<Book> books = [];
getAllEmergenceyContacts()async{
var books = await services.getBook();
}
Then, you Should place all the books inside List view builder like the following way
ListView.builder(
itemCount: books.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(books[index].name),
);
},
),