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");
}
},
);
Related
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;
}
}
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;
}
}
}
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
I have an API response and parsed it using ProductsModel and I am trying to save it to my local storage using Hive and I have different model called LocalProductsModel. How can I cast the response ProductsModel to LocalProductsModel? I used product.cast<LocalProductsModel>();
Here's my Products Model:
class ProductsList{
final List<ProductsModel> products;
ProductsList({this.products});
factory ProductsList.fromJSON(List<dynamic> parsedJson){
List <ProductsModel> productsList = new List<ProductsModel>();
productsList = parsedJson.map((i) => ProductsModel.fromJSON(i)).toList();
return new ProductsList(
products: productsList
);
}
}
class ProductsModel {
final int id;
final String name;
final String catalog_visibility;
final String description;
final String short_description;
final String price;
final String regular_price;
final String sale_price;
final String date_created;
final List<CategoriesModel> categories;
final List<ImagesModel> images;
ProductsModel(
{this.id,
this.name,
this.catalog_visibility,
this.description,
this.short_description,
this.price,
this.regular_price,
this.sale_price,
this.date_created,
this.categories,
this.images
});
factory ProductsModel.fromJSON(Map<String, dynamic> parsedJson) {
var categoriesList = parsedJson['categories'] as List;
var imagesList = parsedJson['images'] as List;
List<ImagesModel> dataImages = imagesList.map((i) => ImagesModel.fromJSON(i)).toList();
List<CategoriesModel> dataCategories =
categoriesList.map((i) => CategoriesModel.fromJSON(i)).toList();
return ProductsModel(
id: parsedJson['id'],
name: parsedJson['name'],
catalog_visibility: parsedJson['catalog_visibility'],
description: parsedJson['description'],
short_description: parsedJson['short_description'],
regular_price: parsedJson['regular_price'],
sale_price: parsedJson['sale_price'],
date_created: parsedJson['date_created'],
categories: dataCategories,
images: dataImages
);
}
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
ImagesModel img = ImagesModel();
map["id"] = id;
map["name"] = name;
map["description"] = description;
map["catalog_visibility"] = catalog_visibility;
map["short_description"] = short_description;
map["regular_price"] = regular_price;
map["sale_price"] = sale_price;
map["date_created"] = date_created;
map['images'] = this.images.map((v) => v.toMap()).toList();
return map;
}
}
class CategoriesModel {
final int id;
final String name;
CategoriesModel({this.id, this.name});
factory CategoriesModel.fromJSON(Map<String, dynamic> parsedJson) {
return CategoriesModel(id: parsedJson['id'], name: parsedJson['name']);
}
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
map["id"] = id;
map["name"] = name;
return map;
}
}
class ImagesModel{
final int id;
final String src;
final String name;
ImagesModel({this.id, this.src, this.name});
factory ImagesModel.fromJSON(Map<String, dynamic> parsedJson){
return ImagesModel(
id: parsedJson['id'],
src: parsedJson['src'],
name: parsedJson['name']
);
}
Map<String, dynamic> toMap() => {
"id": id,
"src": src,
"name" :name,
};
}
My LocalProductModel for my hive local storage:
import 'package:hive/hive.dart';
part 'localProducts.g.dart';
#HiveType(typeId: 0)
class LocalProductsModel {
#HiveField(0)
final int id;
#HiveField(1)
final String name;
#HiveField(2)
final String catalog_visibility;
#HiveField(3)
final String description;
#HiveField(4)
final String short_description;
#HiveField(5)
final String price;
#HiveField(6)
final String regular_price;
#HiveField(7)
final String sale_price;
#HiveField(8)
final String date_created;
#HiveField(9)
final List<LocalCategoriesModel> categories;
#HiveField(10)
final List<LocalImagesModel> images;
LocalProductsModel(
{this.id,
this.name,
this.catalog_visibility,
this.description,
this.short_description,
this.price,
this.regular_price,
this.sale_price,
this.date_created,
this.categories,
this.images
});
factory LocalProductsModel.fromJSON(Map<String, dynamic> parsedJson) {
var categoriesList = parsedJson['categories'] as List;
var imagesList = parsedJson['images'] as List;
List<LocalImagesModel> dataImages = imagesList.map((i) => LocalImagesModel.fromJSON(i)).toList();
List<LocalCategoriesModel> dataCategories =
categoriesList.map((i) => LocalCategoriesModel.fromJSON(i)).toList();
return LocalProductsModel(
id: parsedJson['id'],
name: parsedJson['name'],
catalog_visibility: parsedJson['catalog_visibility'],
description: parsedJson['description'],
short_description: parsedJson['short_description'],
regular_price: parsedJson['regular_price'],
sale_price: parsedJson['sale_price'],
date_created: parsedJson['date_created'],
categories: dataCategories,
images: dataImages
);
}
Map<String,dynamic> toMap() {
var map = new Map<String, dynamic>();
LocalImagesModel img = LocalImagesModel();
Map<String,dynamic> images = img.toMap();
map["id"] = id;
map["name"] = name;
map["description"] = description;
map["catalog_visibility"] = catalog_visibility;
map["short_description"] = short_description;
map["regular_price"] = regular_price;
map["sale_price"] = sale_price;
map["date_created"] = date_created;
map['images'] = this.images.map((v) => v.toMap()).toList();
return map;
}
}
class LocalCategoriesModel {
final int id;
final String name;
LocalCategoriesModel({this.id, this.name});
factory LocalCategoriesModel.fromJSON(Map<String, dynamic> parsedJson) {
return LocalCategoriesModel(id: parsedJson['id'], name: parsedJson['name']);
}
Map<String,dynamic> toMap() {
var map = new Map<String, dynamic>();
map["id"] = id;
map["name"] = name;
return map;
}
}
class LocalImagesModel{
final int id;
final String src;
final String name;
LocalImagesModel({this.id,this.src,this.name});
factory LocalImagesModel.fromJSON(Map<String,dynamic> parsedJson){
return LocalImagesModel(
id: parsedJson['id'],
src: parsedJson['src'],
name: parsedJson['name']
);
}
Map<String, dynamic> toMap() => {
"id": id,
"src": src,
"name" :name,
};
}
I have a working add function on hive but I know this is wrong cause I didn't cast it to my LocalProductsModel:
postCartLocal(ProductsModel products){
Map<String, dynamic> productsMap = products.toMap();
Hive.box('cart').add(productsMap);
}
When I am getting the value I got an error type
'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type
'LocalProductsModel' in type cast
My Code on getting the value on local storage:
Widget _buildListView(){
return ValueListenableBuilder(
valueListenable: Hive.box('cart').listenable(),
builder: (context, snapshot, widget){
return ListView.builder(
itemCount: snapshot.length,
itemBuilder: (context, index) {
final cart = snapshot.getAt(index) as LocalProductsModel;
print('lenght ${cart.name}');
});
}
);
}
This should work:
final cart = snapshot.getAt(index).cast<LocalProductsModel>();