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(() { });
Future builder is not working snapshot data is empty. I want build my catalog with gridview.builder, i think problem might be with my Product class.
And one more question, how to access objects inside the media class in json.
When i print my snapshot.data i got this:
flutter: null
this is my code:
late Future<List<Product>> productFuture = getProducts();
static Future<List<Product>> getProducts() async {
var url = '${Constants.API_URL_DOMAIN}action=catalog&category_id=$id';
final response = await http.get(Uri.parse(url));
print(url);
final body = jsonDecode(response.body);
return body['data'].map<Product>(Product.fromJson).toList();
}
this is my Product class:
class Product {
Product({
required this.id,
required this.name,
required this.categoryName,
required this.media,
});
late final int id;
late final String name;
late final String categoryName;
late final List<Media> media;
Product.fromJson(Map<String, dynamic> json){
id = json['id'];
name = json['name'];
categoryName = json['category_name'];
media = List.from(json['media']).map((e)=>Media.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['name'] = name;
_data['category_name'] = categoryName;
_data['media'] = media.map((e)=>e.toJson()).toList();
return _data;
}
}
class Media {
Media({
required this.id,
required this.productId,
required this.type,
required this.links,
required this.position,
required this.createdAt,
required this.updatedAt,
});
late final int id;
late final int productId;
late final String type;
late final Links links;
late final String position;
late final String createdAt;
late final String updatedAt;
Media.fromJson(Map<String, dynamic> json){
id = json['id'];
productId = json['product_id'];
type = json['type'];
links = Links.fromJson(json['links']);
position = json['position'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['product_id'] = productId;
_data['type'] = type;
_data['links'] = links.toJson();
_data['position'] = position;
_data['created_at'] = createdAt;
_data['updated_at'] = updatedAt;
return _data;
}
}
class Links {
Links({
required this.s3,
required this.cdn,
required this.local,
});
late final String s3;
late final String cdn;
late final Local local;
Links.fromJson(Map<String, dynamic> json){
s3 = json['s3'];
cdn = json['cdn'];
local = Local.fromJson(json['local']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['s3'] = s3;
_data['cdn'] = cdn;
_data['local'] = local.toJson();
return _data;
}
}
class Local {
Local({
required this.full,
required this.thumbnails,
});
late final String full;
late final Thumbnails thumbnails;
Local.fromJson(Map<String, dynamic> json){
full = json['full'];
thumbnails = Thumbnails.fromJson(json['thumbnails']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['full'] = full;
_data['thumbnails'] = thumbnails.toJson();
return _data;
}
}
class Thumbnails {
Thumbnails({
required this.s150,
required this.s350,
required this.s750,
});
late final String s150;
late final String s350;
late final String s750;
Thumbnails.fromJson(Map<String, dynamic> json){
s150 = json['150'];
s350 = json['350'];
s750 = json['750'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['150'] = s150;
_data['350'] = s350;
_data['750'] = s750;
return _data;
}
}
My FutureBuilder
FutureBuilder<List<Product>>(
future: productFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasData) {
final catalog = snapshot.data;
return buildCatalog(catalog!);
} else {
print(snapshot.data);
return Text("No widget to build");
}
},
);
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
I need to get payments array in GetUserModel it returns from nodeJs api with database information
I get with this:
List? payments
Future getCurrentUser() async {
var loginDetails = await SharedService.loginDetails();
email = loginDetails?.data.email;
GetUserRequestModel model = GetUserRequestModel(email: email!);
var currentUserInfo = await APIService.getUserInfo(model);
balance = currentUserInfo.data?.balance;
payments = currentUserInfo.data?.payments; //does not working
print(payments)
}
currentUserInfo gives me everythings but I couldnt get payments array. print(payments)
gives me "Instant of payments" output how can I get payments array properly?
This is UserresponseModel:
import 'dart:convert';
GetUserResponseModel getUserResponseModelJSON(String str) =>
GetUserResponseModel.fromJson(json.decode(str));
class GetUserResponseModel {
GetUserResponseModel({
required this.message,
required this.data,
});
late final String message;
late final Data? data;
GetUserResponseModel.fromJson(Map<String, dynamic> json) {
message = json['message'];
data = (json['data'] != null ? Data.fromJson(json['data']) : null);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['message'] = message;
_data['data'] = data?.toJson();
return _data;
}
}
class Data {
Data({
required this.username,
required this.email,
required this.balance,
required this.date,
required this.payments,
required this.id,
});
late final String username;
late final String email;
late final int balance;
late final String date;
late final List<Payments> payments;
late final String id;
Data.fromJson(Map<String, dynamic> json) {
username = json['username'];
email = json['email'];
balance = json['balance'];
date = json['date'];
payments =
List.from(json['payments']).map((e) => Payments.fromJson(e)).toList();
id = json['id'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['username'] = username;
_data['email'] = email;
_data['balance'] = balance;
_data['date'] = date;
_data['payments'] = payments.map((e) => e.toJson()).toList();
_data['id'] = id;
return _data;
}
}
class Payments {
Payments({
required this.paymentCost,
required this.paymentDate,
required this.id,
});
late final int paymentCost;
late final String paymentDate;
late final String id;
Payments.fromJson(Map<String, dynamic> json) {
paymentCost = json['paymentCost'];
paymentDate = json['paymentDate'];
id = json['_id'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['paymentCost'] = paymentCost;
_data['paymentDate'] = paymentDate;
_data['_id'] = id;
return _data;
}
}
And this is the getUserInfo:
static Future<GetUserResponseModel> getUserInfo(
GetUserRequestModel model) async {
var loginDetails = await SharedService.loginDetails();
Map<String, String> requestHeaders = {
'Content-Type': 'application/json',
'Authorization': 'Basic ${loginDetails!.data.token}'
};
var url = Uri.http(Config.apiURL, Config.getUserInfoAPI);
var response = await client.post(
url,
headers: requestHeaders,
body: jsonEncode(model.toJson()),
);
return getUserResponseModelJSON(response.body);
}
So I think you are looking to print the payments data.
In the payments class you should add
#override
String toString() {
return "";
// Return how you want to print the data. Here you could add for example the JSON output.
}
So the class will look like this
class Payments {
Payments({
required this.paymentCost,
required this.paymentDate,
required this.id,
});
late final int paymentCost;
late final String paymentDate;
late final String id;
Payments.fromJson(Map<String, dynamic> json) {
paymentCost = json['paymentCost'];
paymentDate = json['paymentDate'];
id = json['_id'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['paymentCost'] = paymentCost;
_data['paymentDate'] = paymentDate;
_data['_id'] = id;
return _data;
}
#override
String toString() {
return "${this.paymentCost!} : ${this.paymentDate!} : ${this.id!}";
}
}
I haven't tested this code.
each time I try to send data to API I got the following error:
" Unhandled Exception: Converting object to an encodable object failed: Instance of 'AddProjectModel' ".
I followed the debugger step by step everything went well, and all data are passed correctly. However, when it reaches the jsonEncode() method it gives the above error.
Anyone can help please, thanks in advance.
Here is my AddProjectModel and other models used inside it:
class AddProjectModel {
AddProjectModel({
required this.name,
required this.city,
required this.district,
required this.address,
required this.size,
required this.completionDate,
required this.infrastructureCost,
required this.currencyID,
required this.description,
required this.isHidden,
required this.companies,
required this.facilities,
required this.picture,
});
late final String name;
late final String city;
late final String district;
late final String address;
late final double size;
late final DateTime completionDate;
late final double infrastructureCost;
late final int currencyID;
late final String description;
late final bool isHidden;
late final List<AddProjectCompaniesModel> companies;
late final List<AddEditFacilitiesModel> facilities;
late final List<AddProjectPicturesModel> picture;
AddProjectModel.fromJson(Map<String, dynamic> json) {
name = json['name'];
city = json['city'];
district = json['district'];
address = json['address'];
size = json['size'].toDouble();
completionDate = json['completeDate'];
infrastructureCost = json['infrastructureCost'].toDouble();
currencyID = json['currencyID'];
description = json['description'];
isHidden = json['isHidden'];
companies = List.from(json['companies'])
.map((e) => AddProjectCompaniesModel.fromJson(e))
.toList();
facilities = List.from(json['facilities'])
.map((e) => AddEditFacilitiesModel.fromJson(e))
.toList();
picture = List.from(json['picture'])
.map((e) => AddProjectPicturesModel.fromJson(e))
.toList();
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['name'] = name;
data['city'] = city;
data['district'] = district;
data['address'] = address;
data['size'] = size;
data['completeDate'] = completionDate;
data['infrastructureCost'] = infrastructureCost;
data['currencyID'] = currencyID;
data['description'] = description;
data['isHidden'] = isHidden;
data['companies'] = companies.map((e) => e.toJson()).toList();
data['facilities'] = facilities.map((e) => e.toJson()).toList();
data['picture'] = picture.map((e) => e.toJson()).toList();
return data;
}
}
class AddProjectCompaniesModel {
AddProjectCompaniesModel({
required this.companyId,
});
late final int companyId;
AddProjectCompaniesModel.fromJson(Map<String, dynamic> json) {
companyId = json['companyId'];
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['companyId'] = companyId;
return data;
}
}
class AddEditFacilitiesModel {
AddEditFacilitiesModel({
required this.pool,
required this.gym,
required this.garage,
required this.garden,
required this.roofRoom,
required this.barbecuePlace,
required this.cafeterias,
required this.giftShop,
required this.gamingCenter,
required this.supermarket,
required this.atm,
required this.playGround,
required this.parking,
required this.walkingArea,
required this.pharmacy,
required this.dryCleaning,
required this.spaCenter,
required this.medicalServices,
});
late final bool pool;
late final bool gym;
late final bool garage;
late final bool garden;
late final bool roofRoom;
late final bool barbecuePlace;
late final bool cafeterias;
late final bool giftShop;
late final bool gamingCenter;
late final bool supermarket;
late final bool atm;
late final bool playGround;
late final bool parking;
late final bool walkingArea;
late final bool pharmacy;
late final bool dryCleaning;
late final bool spaCenter;
late final bool medicalServices;
AddEditFacilitiesModel.fromJson(Map<String, dynamic> json) {
pool = json['pool'];
gym = json['gym'];
garage = json['garage'];
garden = json['garden'];
roofRoom = json['roofRoom'];
barbecuePlace = json['barbecuePlace'];
cafeterias = json['cafeterias'];
giftShop = json['giftShop'];
gamingCenter = json['gamingCenter'];
supermarket = json['superMarket'];
atm = json['atm'];
playGround = json['playGround'];
parking = json['parking'];
walkingArea = json['walkingArea'];
pharmacy = json['pharmacy'];
dryCleaning = json['drycleaning'];
spaCenter = json['spacenter'];
medicalServices = json['medicalservices'];
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['pool'] = pool;
data['gym'] = gym;
data['garage'] = garage;
data['garden'] = garden;
data['roofRoom'] = roofRoom;
data['barbecuePlace'] = barbecuePlace;
data['cafeterias'] = cafeterias;
data['giftShop'] = giftShop;
data['gamingCenter'] = gamingCenter;
data['superMarket'] = supermarket;
data['atm'] = atm;
data['playGround'] = playGround;
data['parking'] = parking;
data['walkingArea'] = walkingArea;
data['pharmacy'] = pharmacy;
data['drycleaning'] = dryCleaning;
data['spacenter'] = spaCenter;
data['medicalservices'] = medicalServices;
return data;
}
}
class AddProjectPicturesModel {
AddProjectPicturesModel({
this.url,
required this.file,
this.dateAdded,
});
late String? url;
late final String file;
late String? dateAdded;
AddProjectPicturesModel.fromJson(Map<String, dynamic> json) {
url = json['url'];
file = json['file'];
dateAdded = json['dateAdded'];
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['url'] = url;
data['file'] = file;
data['dateAdded'] = dateAdded;
return data;
}
}
Here is my addProject() method that posts data to API:
static Future<bool> addProject(
String name,
String city,
String district,
String address,
double size,
DateTime completionDate,
double infrastructureCost,
int currencyID,
String description,
bool isHidden,
List<AddProjectCompaniesModel> companies,
List<AddEditFacilitiesModel> facilities,
List<AddProjectPicturesModel> projectPicture,
) async {
AddProjectModel projectModel = AddProjectModel(
name: name,
city: city,
district: district,
address: address,
size: size,
completionDate: completionDate,
infrastructureCost: infrastructureCost,
currencyID: currencyID,
description: description,
isHidden: isHidden,
companies: companies,
facilities: facilities,
picture: projectPicture,
);
final url = Uri.https(APIRoutes.baseURL, APIRoutes.project);
Map<String, String> requestHeaders = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ${secureStorage.token}',
};
final response = await client.post(
url,
headers: requestHeaders,
body: jsonEncode(projectModel),
);
if (response.statusCode == 201) {
print('Success with: ${response.statusCode}');
return true;
} else {
print('Failed with: ${response.statusCode}');
return false;
}
}
The problem was a failer in converting an Object to an encodable Object through the jsonEncode() method "which is supported in dart:convert library".
Here is Flutter explanation for jsonEncode() method
As shown in the figure above, we are only allowed to convert values of type "number, boolean, string, null, list, or a map with string keys". So, the issue in my question was not in the following objects:
List<AddProjectCompaniesModel> companies
List<AddEditFacilitiesModel> facilities
List<AddProjectPicturesModel> projectPicture
because these are of type List and no issues with them. However, the issue was in the following lines of code
DateTime completionDate, // inside addProject(...)
late final DateTime completionDate; // inside AddProjectModel{}
data['completeDate'] = completionDate; // inside toJson() of AddProjectModel{}
Where I am was trying to convert a value of type DateTime and it is not allowed as shown in method explanation in the figure above. Beacuse of that I had to convert the completionDate variable from 'DateTime' to 'String' before converting it to json format. And after that it works fine.
Therfore, the solution is to change this line of code
data['completeDate'] = completionDate; // inside toJson() of AddProjectModel{}
To
data['completeDate'] = completionDate.toString();
I hope my answer was explained enough. Below you can view the whole corrected code.
AddProjectModel and other models used inside it:
class AddProjectModel {
AddProjectModel({
required this.name,
required this.city,
required this.district,
required this.address,
required this.size,
required this.completionDate,
required this.infrastructureCost,
required this.currencyID,
required this.description,
required this.isHidden,
required this.companies,
required this.facilities,
required this.picture,
});
late final String name;
late final String city;
late final String district;
late final String address;
late final double size;
late final DateTime completionDate;
late final double infrastructureCost;
late final int currencyID;
late final String description;
late final bool isHidden;
late final List<AddProjectCompaniesModel> companies;
late final List<AddEditFacilitiesModel> facilities;
late final List<AddProjectPicturesModel> picture;
AddProjectModel.fromJson(Map<String, dynamic> json) {
name = json['name'];
city = json['city'];
district = json['district'];
address = json['address'];
size = json['size'].toDouble();
completionDate = json['completeDate'];
infrastructureCost = json['infrastructureCost'].toDouble();
currencyID = json['currencyID'];
description = json['description'];
isHidden = json['isHidden'];
companies = List.from(json['companies'])
.map((e) => AddProjectCompaniesModel.fromJson(e))
.toList();
facilities = List.from(json['facilities'])
.map((e) => AddEditFacilitiesModel.fromJson(e))
.toList();
picture = List.from(json['picture'])
.map((e) => AddProjectPicturesModel.fromJson(e))
.toList();
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['name'] = name;
data['city'] = city;
data['district'] = district;
data['address'] = address;
data['size'] = size;
data['completeDate'] = completionDate.toSting(); //Only this line changed
data['infrastructureCost'] = infrastructureCost;
data['currencyID'] = currencyID;
data['description'] = description;
data['isHidden'] = isHidden;
data['companies'] = companies.map((e) => e.toJson()).toList();
data['facilities'] = facilities.map((e) => e.toJson()).toList();
data['picture'] = picture.map((e) => e.toJson()).toList();
return data;
}
}
class AddProjectCompaniesModel {
AddProjectCompaniesModel({
required this.companyId,
});
late final int companyId;
AddProjectCompaniesModel.fromJson(Map<String, dynamic> json) {
companyId = json['companyId'];
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['companyId'] = companyId;
return data;
}
}
class AddEditFacilitiesModel {
AddEditFacilitiesModel({
required this.pool,
required this.gym,
required this.garage,
required this.garden,
required this.roofRoom,
required this.barbecuePlace,
required this.cafeterias,
required this.giftShop,
required this.gamingCenter,
required this.supermarket,
required this.atm,
required this.playGround,
required this.parking,
required this.walkingArea,
required this.pharmacy,
required this.dryCleaning,
required this.spaCenter,
required this.medicalServices,
});
late final bool pool;
late final bool gym;
late final bool garage;
late final bool garden;
late final bool roofRoom;
late final bool barbecuePlace;
late final bool cafeterias;
late final bool giftShop;
late final bool gamingCenter;
late final bool supermarket;
late final bool atm;
late final bool playGround;
late final bool parking;
late final bool walkingArea;
late final bool pharmacy;
late final bool dryCleaning;
late final bool spaCenter;
late final bool medicalServices;
AddEditFacilitiesModel.fromJson(Map<String, dynamic> json) {
pool = json['pool'];
gym = json['gym'];
garage = json['garage'];
garden = json['garden'];
roofRoom = json['roofRoom'];
barbecuePlace = json['barbecuePlace'];
cafeterias = json['cafeterias'];
giftShop = json['giftShop'];
gamingCenter = json['gamingCenter'];
supermarket = json['superMarket'];
atm = json['atm'];
playGround = json['playGround'];
parking = json['parking'];
walkingArea = json['walkingArea'];
pharmacy = json['pharmacy'];
dryCleaning = json['drycleaning'];
spaCenter = json['spacenter'];
medicalServices = json['medicalservices'];
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['pool'] = pool;
data['gym'] = gym;
data['garage'] = garage;
data['garden'] = garden;
data['roofRoom'] = roofRoom;
data['barbecuePlace'] = barbecuePlace;
data['cafeterias'] = cafeterias;
data['giftShop'] = giftShop;
data['gamingCenter'] = gamingCenter;
data['superMarket'] = supermarket;
data['atm'] = atm;
data['playGround'] = playGround;
data['parking'] = parking;
data['walkingArea'] = walkingArea;
data['pharmacy'] = pharmacy;
data['drycleaning'] = dryCleaning;
data['spacenter'] = spaCenter;
data['medicalservices'] = medicalServices;
return data;
}
}
class AddProjectPicturesModel {
AddProjectPicturesModel({
this.url,
required this.file,
this.dateAdded,
});
late String? url;
late final String file;
late String? dateAdded;
AddProjectPicturesModel.fromJson(Map<String, dynamic> json) {
url = json['url'];
file = json['file'];
dateAdded = json['dateAdded'];
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['url'] = url;
data['file'] = file;
data['dateAdded'] = dateAdded;
return data;
}
}
addProject() method that posts data to API:
static Future<bool> addProject(
String name,
String city,
String district,
String address,
double size,
DateTime completionDate,
double infrastructureCost,
int currencyID,
String description,
bool isHidden,
List<AddProjectCompaniesModel> companies,
List<AddEditFacilitiesModel> facilities,
List<AddProjectPicturesModel> projectPicture,
) async {
AddProjectModel projectModel = AddProjectModel(
name: name,
city: city,
district: district,
address: address,
size: size,
completionDate: completionDate,
infrastructureCost: infrastructureCost,
currencyID: currencyID,
description: description,
isHidden: isHidden,
companies: companies,
facilities: facilities,
picture: projectPicture,
);
final url = Uri.https(APIRoutes.baseURL, APIRoutes.project);
Map<String, String> requestHeaders = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ${secureStorage.token}',
};
final response = await client.post(
url,
headers: requestHeaders,
body: jsonEncode(projectModel),
);
if (response.statusCode == 201) {
print('Success with: ${response.statusCode}');
return true;
} else {
print('Failed with: ${response.statusCode}');
return false;
}
}
That's because dart objects are not convertable to json by default, you need to convert it to Map first or you can use plugins to convert your objects to maps such as json_serializable