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,),
Related
Heelo! I'm new here on StackOverflow. I'm building an application and I have the following problem:
I'm having trouble converting a Map to a List in Flutter:
My function (convert the model with data to List):
insertFinance(FinancialsModel data) {
final dataModel = financials_local.FinancialsLocalModel(
period: data.period,
date: data.date,
costCenter: financials_local.LocalCostCenter(id: data.costCenter!.id),
description: data.description,
quantity: data.quantity,
value: data.value,
unitValue: data.unitValue,
validated: data.validated,
status: data.status,
type: data.type,
harvest: financials_local.LocalCostCenter(id: data.harvest!.id),
customer: financials_local.LocalCostCenter(id: data.customer!.id),
farm: financials_local.LocalCostCenter(id: data.farm!.id),
createdBy: financials_local.LocalCostCenter(id: data.createdBy!.id),
environment: data.environment,
sent: false);
List list = dataModel
.toJson()
.entries
.map<financials_local.LocalCostCenter>((x) => financials_local.LocalCostCenter.fromJson(x))
.toList();
My model:
class FinancialsLocalModel {
String? period;
String? date;
LocalCostCenter? costCenter;
String? description;
int? quantity;
double? value;
double? unitValue;
bool? validated;
bool? status;
String? type;
LocalCostCenter? harvest;
LocalCostCenter? customer;
LocalCostCenter? farm;
LocalCostCenter? createdBy;
String? environment;
bool? sent;
FinancialsLocalModel(
{this.period,
this.date,
this.costCenter,
this.description,
this.quantity,
this.value,
this.unitValue,
this.validated,
this.status,
this.type,
this.harvest,
this.customer,
this.farm,
this.createdBy,
this.environment,
this.sent});
FinancialsLocalModel.fromJson(Map<String, dynamic> json) {
period = json['period'];
date = json['date'];
costCenter = json['cost_center'] != null
? LocalCostCenter.fromJson(json['cost_center'])
: null;
description = json['description'];
quantity = json['quantity'];
value = json['value'];
unitValue = json['unit_value'];
validated = json['validated'];
status = json['status'];
type = json['type'];
harvest = json['harvest'] != null
? LocalCostCenter.fromJson(json['harvest'])
: null;
customer = json['customer'] != null
? LocalCostCenter.fromJson(json['customer'])
: null;
farm = json['farm'] != null ? LocalCostCenter.fromJson(json['farm']) : null;
createdBy = json['created_by'] != null
? LocalCostCenter.fromJson(json['created_by'])
: null;
environment = json['environment'];
sent = (json['sent'] == 0) ? false : true;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['period'] = period;
data['date'] = date;
if (costCenter != null) {
data['cost_center'] = costCenter!.toJson();
}
data['description'] = description;
data['quantity'] = quantity;
data['value'] = value;
data['unit_value'] = unitValue;
data['validated'] = validated;
data['status'] = status;
data['type'] = type;
if (harvest != null) {
data['harvest'] = harvest!.toJson();
}
if (customer != null) {
data['customer'] = customer!.toJson();
}
if (farm != null) {
data['farm'] = farm!.toJson();
}
if (createdBy != null) {
data['created_by'] = createdBy!.toJson();
}
data['environment'] = environment;
data['sent'] = (!sent!) ? 0 : 1;
return data;
}
}
class LocalCostCenter {
int? id;
LocalCostCenter({this.id});
LocalCostCenter.fromJson(Map<String, dynamic> json) {
id = json['id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['id'] = id;
return data;
}
}
This is the error that appears when running the code:
Error: The argument type 'MapEntry<String, dynamic>' can't be
assigned to the parameter type 'Map<String, dynamic>'.
Looks like you are trying to get all the LocalCostCenter fields of FinancialsLocalModel and make a list of them.
Try changing your function to this:
insertFinance(FinancialsModel data) {
final dataModel = financials_local.FinancialsLocalModel(
...
);
final dataModelMap = dataModel.toJson();
final dataModelMapCopy = Map<String, dynamic>.from(dataModelMap); // Copy of dataModelMap
dataModelMapCopy.removeWhere((key, value) => value is! Map); // Only including the records with the type of LocalCostCenter
List<financials_local.LocalCostCenter> list = dataModelMapCopy.values.map((e) => financials_local.LocalCostCenter.fromJson(e)).toList(); // A list of all LocalCostCenter fields of dataModel
}
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(() { });
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
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;
}
}
Future<bool> login({username, password}) async {
var api = API();
_status = LoginStatus.loading;
notifyListeners();
var url = Uri.parse(api.baseUrl + api.auth);
final response = await http.post(
url,
body: jsonEncode({
"identifier": "$username",
"password": "$password",
}),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
);
if (response.statusCode == 200) {
final parsed = jsonDecode(response.body).cast<Map<String, dynamic>>();
parsed
.map<UserModel>((json) => UserModel.fromJson(json))
.toList();
final token = jsonDecode(response.body)['jwt'];
print(token);
await saveToken(token);
return true;
} else {
_status = LoginStatus.error;
_error = response.body;
notifyListeners();
return false;
}
}
Code Screen Shot
How Should I save this parsed JSON to UserModel? I have encountered many problems and figured out many things on my own but I am not yet able to add data to the model.
By the way I am using strapi as a back end and every api is working. And I amso use a website called json to dart converter so that my models are correct(As I Assume).
Please help !!!!!!!!!!!!
UserModel
class UserModel {
User user;
UserModel({this.user});
UserModel.fromJson(Map<String, dynamic> json) {
user = json['user'] != null ? new User.fromJson(json['user']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.user != null) {
data['user'] = this.user.toJson();
}
return data;
}
}
class User {
int id;
String username;
String email;
String provider;
bool confirmed;
bool blocked;
Role role;
String displayName;
String createdAt;
String updatedAt;
Avatar avatar;
List<UserCategories> userCategories;
User(
{this.id,
this.username,
this.email,
this.provider,
this.confirmed,
this.blocked,
this.role,
this.displayName,
this.createdAt,
this.updatedAt,
this.avatar,
this.userCategories});
User.fromJson(Map<String, dynamic> json) {
id = json['id'];
username = json['username'];
email = json['email'];
provider = json['provider'];
confirmed = json['confirmed'];
blocked = json['blocked'];
role = json['role'] != null ? new Role.fromJson(json['role']) : null;
displayName = json['displayName'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
avatar =
json['avatar'] != null ? new Avatar.fromJson(json['avatar']) : null;
if (json['user_categories'] != null) {
userCategories = new List<UserCategories>();
json['user_categories'].forEach((v) {
userCategories.add(new UserCategories.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['username'] = this.username;
data['email'] = this.email;
data['provider'] = this.provider;
data['confirmed'] = this.confirmed;
data['blocked'] = this.blocked;
if (this.role != null) {
data['role'] = this.role.toJson();
}
data['displayName'] = this.displayName;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
if (this.avatar != null) {
data['avatar'] = this.avatar.toJson();
}
if (this.userCategories != null) {
data['user_categories'] =
this.userCategories.map((v) => v.toJson()).toList();
}
return data;
}
}
class Role {
int id;
String name;
String description;
String type;
Role({this.id, this.name, this.description, this.type});
Role.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
description = json['description'];
type = json['type'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['description'] = this.description;
data['type'] = this.type;
return data;
}
}
class Avatar {
int id;
String name;
String alternativeText;
String caption;
int width;
int height;
Formats formats;
String hash;
String ext;
String mime;
double size;
String url;
Null previewUrl;
String provider;
Null providerMetadata;
String createdAt;
String updatedAt;
Avatar(
{this.id,
this.name,
this.alternativeText,
this.caption,
this.width,
this.height,
this.formats,
this.hash,
this.ext,
this.mime,
this.size,
this.url,
this.previewUrl,
this.provider,
this.providerMetadata,
this.createdAt,
this.updatedAt});
Avatar.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
alternativeText = json['alternativeText'];
caption = json['caption'];
width = json['width'];
height = json['height'];
formats =
json['formats'] != null ? new Formats.fromJson(json['formats']) : null;
hash = json['hash'];
ext = json['ext'];
mime = json['mime'];
size = json['size'];
url = json['url'];
previewUrl = json['previewUrl'];
provider = json['provider'];
providerMetadata = json['provider_metadata'];
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['name'] = this.name;
data['alternativeText'] = this.alternativeText;
data['caption'] = this.caption;
data['width'] = this.width;
data['height'] = this.height;
if (this.formats != null) {
data['formats'] = this.formats.toJson();
}
data['hash'] = this.hash;
data['ext'] = this.ext;
data['mime'] = this.mime;
data['size'] = this.size;
data['url'] = this.url;
data['previewUrl'] = this.previewUrl;
data['provider'] = this.provider;
data['provider_metadata'] = this.providerMetadata;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
class Formats {
Thumbnail thumbnail;
Formats({this.thumbnail});
Formats.fromJson(Map<String, dynamic> json) {
thumbnail = json['thumbnail'] != null
? new Thumbnail.fromJson(json['thumbnail'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.thumbnail != null) {
data['thumbnail'] = this.thumbnail.toJson();
}
return data;
}
}
class Thumbnail {
String name;
String hash;
String ext;
String mime;
int width;
int height;
double size;
Null path;
String url;
Thumbnail(
{this.name,
this.hash,
this.ext,
this.mime,
this.width,
this.height,
this.size,
this.path,
this.url});
Thumbnail.fromJson(Map<String, dynamic> json) {
name = json['name'];
hash = json['hash'];
ext = json['ext'];
mime = json['mime'];
width = json['width'];
height = json['height'];
size = json['size'];
path = json['path'];
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['hash'] = this.hash;
data['ext'] = this.ext;
data['mime'] = this.mime;
data['width'] = this.width;
data['height'] = this.height;
data['size'] = this.size;
data['path'] = this.path;
data['url'] = this.url;
return data;
}
}
class UserCategories {
int id;
String categoryName;
int usersPermissionsUser;
String publishedAt;
String createdAt;
String updatedAt;
UserCategories(
{this.id,
this.categoryName,
this.usersPermissionsUser,
this.publishedAt,
this.createdAt,
this.updatedAt});
UserCategories.fromJson(Map<String, dynamic> json) {
id = json['id'];
categoryName = json['categoryName'];
usersPermissionsUser = json['users_permissions_user'];
publishedAt = json['published_at'];
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['categoryName'] = this.categoryName;
data['users_permissions_user'] = this.usersPermissionsUser;
data['published_at'] = this.publishedAt;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
The UserModel.fromJson method will only work if the response.body content is a User, so to fix your issue, instead of using UserModel.fromJson on the response.body json decoded variable, rather use the fromJson() function on data that you are sure will conform to your class definition.
For example:
class User{
final String name;
final String surname;
final String email;
User({this.name, this.surname, this.email});
factory User.fromJson(Map<String,dynamic> json){
return User(
'name': json['name'],
'surname': json['surname'],
'email': json['email']
);
}
}
The json response that is recieved from the api:
{
"name" : "John",
"surname": "Smith",
"email": "johnsmith#mail.com"
}
In your function, decode response and cast to the User model class:
final parsed = jsonDecode(response.body); // or Map<String,dynamic> parsed = jsonDecode(response.body);
User user = User.fromJson(parsed)