Get User Model Array List - flutter

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.

Related

Flutter type '(dynamic) => Search' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform'

I am trying to make a search function but I am getting the following error: type '(dynamic) => Search' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform', the function in which the error:
static Future<List<Search>> searchProducts(String search) async {
var url =
'${Constants.API_URL_DOMAIN}action=search&token=${Constants.USER_TOKEN}&q=$search';
final response = await http.get(Uri.parse(url));
final body = jsonDecode(response.body);
print(url);
return List.from(body['data'].map((e) => Search.fromJson(e)).toList());
}
late Future<List<Search>> searchFuture = Func.searchProducts(searchController.text);
Widget buildSearch() => FutureBuilder<List<Search>>(
future: searchFuture,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
children: [
Text('test')
],
);
} else {
print(snapshot.error);
print('error');
return const Text('error');
}
}
);
I can't figure out where this error comes from, I have similar functions in other parts of the code and they work fine.
My Search class :
class Search {
Search({
required this.products,
required this.categories,
});
late final Products products;
late final Categories categories;
Search.fromJson(Map<String, dynamic> json){
products = Products.fromJson(json['products']);
categories = Categories.fromJson(json['categories']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['products'] = products.toJson();
_data['categories'] = categories.toJson();
return _data;
}
}
class Products {
Products({
required this.total,
required this.items,
});
late final int total;
late final List<Items> items;
Products.fromJson(Map<String, dynamic> json){
total = json['total'];
items = List.from(json['items']).map((e)=>Items.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['total'] = total;
_data['items'] = items.map((e)=>e.toJson()).toList();
return _data;
}
}
class Items {
Items({
required this.id,
required this.name,
required this.isFavorite,
required this.price,
required this.link,
this.media,
});
late final int id;
late final String name;
late final bool isFavorite;
late final int price;
late final String link;
late final List<Media>? media;
Items.fromJson(Map<String, dynamic> json){
id = json['id'];
name = json['name'];
isFavorite = json['is_favorite'];
price = json['price'];
link = json['link'];
media = null;
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['name'] = name;
_data['is_favorite'] = isFavorite;
_data['price'] = price;
_data['link'] = link;
_data['media'] = media;
return _data;
}
}
class Media {
Media({
required this.id,
required this.productId,
required this.type,
required this.links,
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 Null 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 = null;
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({
this.s3,
this.cdn,
required this.local,
});
late final Null s3;
late final Null cdn;
late final Local local;
Links.fromJson(Map<String, dynamic> json){
s3 = null;
cdn = null;
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'] = 150;
_data['350'] = 350;
_data['750'] = 750;
return _data;
}
}
class Categories {
Categories({
required this.total,
required this.items,
});
late final int total;
late final List<Items> items;
Categories.fromJson(Map<String, dynamic> json){
total = json['total'];
items = List.from(json['items']).map((e)=>Items.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['total'] = total;
_data['items'] = items.map((e)=>e.toJson()).toList();
return _data;
}
}

How to save this nested class in Isar DB Flutter

I have the following 4 classes. In this, only the ProductGroup is saved, ProductVariant, ProductSize and ProductColor are not stored. Please help me with this.
product_group.dart
#Collection()
class ProductGroup {
late Id id;
#Index(caseSensitive: false)
late String productGroupName;
final productVariants = IsarLinks<ProductVariant>();
ProductGroup();
ProductGroup.fromJson(Map<String, dynamic> json) {
id = json['Id'];
productGroupName = json['PG'];
if (json['Ps'] != null) {
json['Ps'].forEach((variant) {
productVariants.add(ProductVariant.fromJson(variant));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['Id'] = id;
data['PG'] = productGroupName;
data['Ps'] = productVariants.map((variant) => variant.toJson()).toList();
return data;
}
}
product_variant.dart
#Collection()
class ProductVariant {
late Id id;
late String variantName;
final productSizes = IsarLinks<ProductSize>();
ProductVariant();
ProductVariant.fromJson(Map<String, dynamic> json) {
id = json['Id'];
variantName = json['St'];
if (json['Ss'] != null) {
json['Ss'].forEach((v) {
productSizes.add(ProductSize.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['Id'] = id;
data['St'] = variantName;
data['Ss'] = productSizes.map((v) => v.toJson()).toList();
return data;
}
}
product_size.dart
#Collection()
class ProductSize {
late Id id;
late String size;
final productColors = IsarLinks<ProductColor>();
ProductSize();
ProductSize.fromJson(Map<String, dynamic> json) {
id = json['Id'];
size = json['S'];
if (json['Cs'] != null) {
json['Cs'].forEach((v) {
productColors.add(ProductColor.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['Id'] = id;
data['S'] = size;
data['Cs'] = productColors.map((color) => color.toJson()).toList();
return data;
}
}
product_color.dart
#Collection()
class ProductColor {
late Id id;
late String colorName;
late String colorHexCode;
ProductColor();
ProductColor.fromJson(Map<String, dynamic> json) {
id = json['Id'];
colorName = json['C'];
colorHexCode = json['CC'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['Id'] = id;
data['C'] = colorName;
data['CC'] = colorHexCode;
return data;
}
}
I am parsing the json and saving it in Isar
convertJsonToIsar() async {
try {
// For testing purposes, loading Json from assets, in Prod, Json will be fetched from server
final String response = await rootBundle.loadString('assets/pr_dump.json');
final data = await json.decode(response);
List<ProductGroup> productGroupList = [];
data.forEach((item) {
productGroupList.add(ProductGroup.fromJson(item));
});
Isar _isar = getIsar();
_isar.writeTxnSync(() {
_isar.productGroups.putAllSync(productGroupList, saveLinks: true);
});
} catch (e) {
// Handle Error
print('Caught Error');
print(e.toString());
return 0;
}
}
Only the ProductGroup is stored, ProductVariant, ProductSize and ProductColor are not stored. Please help me with this.

Future builder error, snapshot data empty

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");
}
},
);

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: Unhandled Exception: Converting object to an encodable object failed: Instance of 'AddProjectModel'

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