Flutter model json - flutter

How do I retrieve the information in the address? Attempted to retrieve information I can fetch but the Items class part is not fetching the address part. I'm practicing the fetch api.
I'm not sure if what I'm doing is correct. or may be stuck with some part of the problem i try to fix please help me
List<Items> _list = [];
List<Items> _search = [];
var loading = false;
Future fetchMos() async {
setState(() {
loading = true;
});
_list.clear();
var client = http.Client();
String mosUrl =
'';
var url = Uri.parse(mosUrl);
var headers = {'Client-Token': ''};
var response = await client.get(url, headers: headers);
if (response.statusCode == 200) {
var data = jsonDecode((utf8.decode(response.bodyBytes)))['items'];
setState(() {
for (Map i in data) {
_list.add(Items.fromJson(i));
loading = false;
}
});
}
}
This is class model
class Items {
String? custnum;
String? name;
List<Address>? address;
Items({this.custnum, this.name, this.address});
Items.fromJson(json) {
custnum = json['custnum'];
name = json['name'];
if (json['address'] != null) {
address = <Address>[];
json['address'].forEach((v) {
address!.add(new Address.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['custnum'] = this.custnum;
data['name'] = this.name;
if (this.address != null) {
data['address'] = this.address!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Address {
int? shipto;
String? addr1;
String? thanon;
String? tambon;
String? amphur;
String? provCode;
String? province;
String? country;
String? phone;
String? email;
String? postcode;
String? contact;
String? latitude;
String? longitude;
String? fax;
String? soi;
Address(
{this.shipto,
this.addr1,
this.thanon,
this.tambon,
this.amphur,
this.provCode,
this.province,
this.zipcode,
this.country,
this.phone,
this.email,
this.postcode,
this.contact,
this.latitude,
this.longitude,
this.fax,
this.soi});
Address.fromJson(json) {
shipto = json['shipto'];
addr1 = json['addr1'];
thanon = json['thanon'];
tambon = json['tambon'];
amphur = json['amphur'];
provCode = json['prov_code'];
province = json['province'];
zipcode = json['zipcode'];
country = json['country'];
phone = json['phone'];
email = json['email'];
postcode = json['postcode'];
contact = json['contact'];
latitude = json['latitude'];
longitude = json['longitude'];
fax = json['fax'];
soi = json['soi'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['shipto'] = this.shipto;
data['addr1'] = this.addr1;
data['thanon'] = this.thanon;
data['tambon'] = this.tambon;
data['amphur'] = this.amphur;
data['prov_code'] = this.provCode;
data['province'] = this.province;
data['zipcode'] = this.zipcode;
data['phone'] = this.phone;
data['email'] = this.email;
data['postcode'] = this.postcode;
data['contact'] = this.contact;
data['longitude'] = this.longitude;
data['fax'] = this.fax;
data['soi'] = this.soi;
return data;
}
}

var data =json.decode(response.body);
for (var i in data['items']) {
_list.add(Items.fromJson(i));
loading = false;
}
setState(() { });

Related

How to solve Closure: () => int in flutter?

I have a case like this and I don't understand why this is happening, because the console does not give an error message.
I want to sum up the data in the API but the output is as follows.
Here I do the sum
int getSum() {
int? uts = int.tryParse(data.first.nilaiIndeksUts ?? '');
int? akhir = int.tryParse(data.first.nilaiIndeksAkhir ?? '');
return (uts ?? 0) + (akhir ?? 0);
}
I call getSum in here
Text(
'$getSum',
style: bold6,
),
and this is the model I made from API, I still haven't found the solution for days.
Has anyone here ever experienced a similar case or have done a summation of data in the API?
Thank you in advance.
class NilaiMahasiswa {
String? status;
String? code;
List<Data>? data;
NilaiMahasiswa({this.status, this.code, this.data});
NilaiMahasiswa.fromJson(Map<String, dynamic> json) {
status = json['status'];
code = json['code'];
if (json['data'] != null) {
data = <Data>[];
json['data'].forEach((v) {
data!.add(Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['status'] = status;
data['code'] = code;
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
String? idTranskripNilai;
String? idMk;
String? kodeMk;
String? nmMk;
int? sks;
int? smt;
String? nilaiAkhirUts;
String? nilaiHurufUts;
String? nilaiIndeksUts;
String? nilaiAkhirUas;
String? nilaiAkhir;
String? nilaiHurufAkhir;
String? nilaiIndeksAkhir;
int? statusNilaiAkhir;
int? statusNilaiUts;
String? updatedBy;
Data(
{this.idTranskripNilai,
this.idMk,
this.kodeMk,
this.nmMk,
this.sks,
this.smt,
this.nilaiAkhirUts,
this.nilaiHurufUts,
this.nilaiIndeksUts,
this.nilaiAkhirUas,
this.nilaiAkhir,
this.nilaiHurufAkhir,
this.nilaiIndeksAkhir,
this.statusNilaiAkhir,
this.statusNilaiUts,
this.updatedBy});
Data.fromJson(Map<String, dynamic> json) {
idTranskripNilai = json['id_transkrip_nilai'];
idMk = json['id_mk'];
kodeMk = json['kode_mk'];
nmMk = json['nm_mk'];
sks = json['sks'];
smt = json['smt'];
nilaiAkhirUts = json['nilai_akhir_uts'];
nilaiHurufUts = json['nilai_huruf_uts'];
nilaiIndeksUts = json['nilai_indeks_uts'];
nilaiAkhirUas = json['nilai_akhir_uas'];
nilaiAkhir = json['nilai_akhir'];
nilaiHurufAkhir = json['nilai_huruf_akhir'];
nilaiIndeksAkhir = json['nilai_indeks_akhir'];
statusNilaiAkhir = json['status_nilai_akhir'];
statusNilaiUts = json['status_nilai_uts'];
updatedBy = json['updated_by'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['id_transkrip_nilai'] = idTranskripNilai;
data['id_mk'] = idMk;
data['kode_mk'] = kodeMk;
data['nm_mk'] = nmMk;
data['sks'] = sks;
data['smt'] = smt;
data['nilai_akhir_uts'] = nilaiAkhirUts;
data['nilai_huruf_uts'] = nilaiHurufUts;
data['nilai_indeks_uts'] = nilaiIndeksUts;
data['nilai_akhir_uas'] = nilaiAkhirUas;
data['nilai_akhir'] = nilaiAkhir;
data['nilai_huruf_akhir'] = nilaiHurufAkhir;
data['nilai_indeks_akhir'] = nilaiIndeksAkhir;
data['status_nilai_akhir'] = statusNilaiAkhir;
data['status_nilai_uts'] = statusNilaiUts;
data['updated_by'] = updatedBy;
return data;
}
}
getSum is a function, you need to add () to call it and return integer value.
Text( '${getSum()}', style: bold6,),

Format Exception: Unexpected Character (at character 1)Instance of 'VerifyData'

Why does this code give me this error? In the emulator, I have this problem Format Exception: Unexpected Character (at character 1)Instance of 'VerifyData'. I don't know resolve of this.
static VerifyData? fromObject(Object? data) {
try {
if (data != null) {
var jsonObject = json.decode(data.toString());
return VerifyData.fromJson(jsonObject);
}
} catch (e) {
return null;
}
}
this is class VerifyData and json. what's wrong in this my code? because I think it is in accordance with the contents of the API that I have made
class VerifyData {
int? id;
String? user;
String? name;
String? level;
String? photo;
String? email;
String? phone;
String? address;
String? time;
String? v;
int? iat;
int? exp;
VerifyData(
{this.id,
this.user,
this.name,
this.level,
this.photo,
this.email,
this.phone,
this.address,
this.time,
this.v,
this.iat,
this.exp});
VerifyData.fromJson(Map<String, dynamic> json) {
id = json['id'];
user = json['user'];
name = json['name'];
level = json['level'];
photo = json['photo'];
email = json['email'];
phone = json['phone'];
address = json['address'];
time = json['time'];
v = json['v'];
iat = json['iat'];
exp = json['exp'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['user'] = this.user;
data['name'] = this.name;
data['level'] = this.level;
data['photo'] = this.photo;
data['email'] = this.email;
data['phone'] = this.phone;
data['address'] = this.address;
data['time'] = this.time;
data['v'] = this.v;
data['iat'] = this.iat;
data['exp'] = this.exp;
return data;
}
I/flutter ( 5881): Data : {"id":1,"user":"admin","name":"Admin","level":"employee","photo":null,"email":"admin#gmail.com","phone":null,"address":"Jl. Asem Daerah","time":"2022-10-11T02:34:55.138Z","v":"p","iat":1122355694,"exp":1122259294}
You might want to check this out: https://docs.flutter.dev/development/data-and-backend/json

Storing API Response in Flutter

I'm following an online trutorial to attempt to gain a better understanding of retreiving an API and storing it's response body to Hive.
In the online example i'm using i encounter an issue when attempting to store my response body. This is the error that i get;
Could any one give me any pointers to what i'm doing wrong?
My model
import 'package:hive_flutter/hive_flutter.dart';
part 'hive_solUser.g.dart';
#HiveType(typeId: 0) //, adapterName: "SolUserAdapter")
class GetSolUser {
#HiveField(0)
String? solUsername;
#HiveField(1)
bool? isUserActive;
#HiveField(2)
String? solSessionKey;
#HiveField(3)
String? firstame;
#HiveField(4)
String? lastName;
#HiveField(5)
int? id;
#HiveField(6)
String? email;
GetSolUser(
{required this.solUsername,
required this.isUserActive,
required this.solSessionKey,
required this.firstame,
required this.lastName,
required this.id,
required this.email});
GetSolUser.fromJson(Map<String, dynamic> json) {
solUsername = json['username'];
isUserActive = json['isUserActive'];
solSessionKey = json['solSessionKey'];
firstame = json['firstame'];
lastName = json['lastName'];
id = json['id'];
email = json['email'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['username'] = solUsername;
data['isUserActive'] = isUserActive;
data['solSessionKey'] = solSessionKey;
data['firstame'] = firstame;
data['lastName'] = lastName;
data['id'] = id;
data['email'] = email;
return data;
}
}
API Service
class APIServiceSolUser {
Future<bool> getSolUser(BuildContext context) async {
log("Requesting Sol User List...");
var solUserListResponse = await HTTPHandler()
.httpRequest(url: solUserURL, method: RequestType.GET);
final response = await http.get(Uri.parse(solUserURL));
//final solUserListResponse = jsonDecode(response.body);
if (response.statusCode != 200) {
return false;
} else {
log("Sol User API RESPONSE SUCCESSFUL");
var data = json.decode(response.body);
var data1 = solUserListResponse;
List<GetSolUser> solUserList =
List.from(data1.map((users) => GetSolUser.fromJson(users)));
await GetSolUserProvider().updateSolUserData(solUserList);
await GetSolUserProvider().saveOfflineData(solUserList);
return true;
}
}
}

Flutter firebase data model

class AllRideRequest {
String? name;
String? destinationAddress;
DriverLocation? driverLocation;
AllRideRequest({
this.name,
this.destinationAddress, this.driverLocation
});
AllRideRequest.fromSnapshot(DataSnapshot dataSnapshot) {
name = (dataSnapshot.value as Map)["userName"];
destinationAddress = (dataSnapshot.value as Map)["destinationAddress"];
driverLocation = DriverLocation.fromSnapshot(dataSnapshot);
}
}
class DriverLocation {
double? latitude;
double? longitude;
DriverLocation({
this.latitude,
this.longitude,
});
DriverLocation.fromSnapshot(DataSnapshot dataSnapshot) {
latitude = (dataSnapshot.value as Map)["latitude"];
longitude = (dataSnapshot.value as Map)["longitude"];
}
}
i have a data model like this. Name and destinationAddress has a value but DriverLocation lat long null how can i fix this problem
i want to reach this
https://i.stack.imgur.com/WsoOF.png
Check this
class ResponseData {
String? userName;
String? destinationAddress;
DriverLocation? driverLocation;
ResponseData({this.userName, this.destinationAddress, this.driverLocation});
ResponseData.fromJson(Map<String, dynamic> json) {
userName = json['userName'];
destinationAddress = json['destinationAddress'];
driverLocation = json['driverLocation'] != null
? new DriverLocation.fromJson(json['driverLocation'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['userName'] = this.userName;
data['destinationAddress'] = this.destinationAddress;
if (this.driverLocation != null) {
data['driverLocation'] = this.driverLocation!.toJson();
}
return data;
}
}
class DriverLocation {
String? latitude;
String? longitude;
DriverLocation({this.latitude, this.longitude});
DriverLocation.fromJson(Map<String, dynamic> json) {
latitude = json['latitude'];
longitude = json['longitude'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['latitude'] = this.latitude;
data['longitude'] = this.longitude;
return data;
}
}

How assign object correctly flutter

Hello i'm working on flutter project .
I have a class :
class Data {
RevisionInProgress revisionInProgress;
Data({this.revisionInProgress});
Data.fromJson(Map<String, dynamic> json) {
revisionInProgress = json['revision in progress'] != null
? new RevisionInProgress.fromJson(json['revision in progress'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.revisionInProgress != null) {
data['revision in progress'] = this.revisionInProgress.toJson();
}
return data;
}
}
class Datum {
int id;
int boxId;
int userId;
String revisionType;
String revisionDate;
String revisionLocation;
String revisionTitle;
int kilometragePourVidange;
int repeatRevision;
int revisionStatus;
String kilometrageLastVidange;
int kilometrageRevision;
String createdAt;
String updatedAt;
Datum(
{this.id,
this.boxId,
this.userId,
this.revisionType,
this.revisionDate,
this.revisionLocation,
this.revisionTitle,
this.kilometragePourVidange,
this.repeatRevision,
this.revisionStatus,
this.kilometrageLastVidange,
this.kilometrageRevision,
this.createdAt,
this.updatedAt});
Datum.fromJson(Map<String, dynamic> json) {
id = json['id'];
boxId = json['box_id'];
userId = json['user_id'];
revisionType = json['revision_type'];
revisionDate = json['revision_date'];
revisionLocation = json['revision_location'];
revisionTitle = json['revision_title'];
kilometragePourVidange = json['kilometrage_pour_vidange'];
repeatRevision = json['repeat_revision'];
revisionStatus = json['revision_status'];
kilometrageLastVidange = json['kilometrage_last_vidange'];
kilometrageRevision = json['Kilometrage_revision'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['box_id'] = this.boxId;
data['user_id'] = this.userId;
data['revision_type'] = this.revisionType;
data['revision_date'] = this.revisionDate;
data['revision_location'] = this.revisionLocation;
data['revision_title'] = this.revisionTitle;
data['kilometrage_pour_vidange'] = this.kilometragePourVidange;
data['repeat_revision'] = this.repeatRevision;
data['revision_status'] = this.revisionStatus;
data['kilometrage_last_vidange'] = this.kilometrageLastVidange;
data['Kilometrage_revision'] = this.kilometrageRevision;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
After assigning values:
Datum datum = Datum();
void setRevision() async {
print(_EmplacementController.text);
print(_DateController.text);
print(status.toString());
if (_formKey.currentState.validate()) {
datum.revisionType = status.toString();
datum.revisionTitle = _eventController.text;
datum.revisionDate = _DateController.text;
datum.revisionLocation = _EmplacementController.text;
datum.kilometragePourVidange = num.parse(_KilometrageController.text);
datum.repeatRevision = status1;
datum.kilometrageRevision =
num.parse(_Kilometrage_revisionController.text);
print(datum.revisionDate);
print(datum.revisionLocation);
revisionApi
.setRevision(
datum.revisionTitle,
datum.revisionType,
datum.revisionDate,
datum.revisionLocation,
datum.repeatRevision,
datum.kilometrageRevision,
datum.kilometragePourVidange,
)
.then((data) {
if (data != null) {
}
}).catchError((error) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(error.toString())));
});
setState(() {});
Navigator.pop(context);
//
}
}
My problem is when i inspect _EmplacementController.text before assign => it show me the correct value . but if i inspect datum.revisionDate after assign ==> it show me nothing .
datum.revisionDate ==> empty
datum.revisionLocation ==> empty
How i can correct it ?
thanks in advance
If your form is validated then you have to save the form.
bool _validateAndSaveForm() {
final form = _formKey.currentState;
if (form.validate()) {
form.save();
return true;
}
return false;
}
if (_validateAndSaveForm()) {
datum.revisionType = status.toString();
datum.revisionTitle = _eventController.text;
datum.revisionDate = _DateController.text;
datum.revisionLocation = _EmplacementController.text;
datum.kilometragePourVidange = num.parse(_KilometrageController.text);
datum.repeatRevision = status1;
datum.kilometrageRevision =
num.parse(_Kilometrage_revisionController.text);