Related
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
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 fetch data from firebase and I want to sort the date data I receive by date. The object I receive look like the following:
Appointment Model
class MAppointment with ChangeNotifier {
String id;
String title;
String location;
DateTime createdAt;
String email;
List<Events> events;
List<Participants> participants;
String nameOriginater;
MAppointment({
this.id,
this.title,
this.location,
this.createdAt,
this.email,
this.events,
this.participants,
this.nameOriginater,
});
MAppointment.fromMap(Map<String, dynamic> data) {
id = data['id'];
title = data['title'];
location = data['location'];
createdAt = data['created_at'];
email = data['email'];
events =
List.from(data['events']).map((item) => Events.fromMap(item)).toList();
participants = List.from(data['participants'])
.map((item) => Participants.fromMap(item))
.toList();
nameOriginater = data['name'];
}
}
Event Model
class Events with ChangeNotifier {
DateTime end;
String name;
DateTime start;
bool timed;
Events(this.end, this.name, this.start, this.timed);
Events.fromMap(Map<dynamic, dynamic> data) {
end = data['end'];
name = data['name'];
start = data['start'];
timed = data['timed'];
}
Map<dynamic, dynamic> toMap() {
return {'end': end, 'name': name, 'start': start, 'timed': timed};
}
}
I later get the MAppointment by the provider as items (List<MAppointment> items).
How can I order the event part by date for items[0].events? The reference for the sort should be items[0].events[0].start
I have two model classes Employee and AdditionalDetails
class Employee{
AdditionalDetails(this.uuid, this.additional_details);
String uuid;
String additional_details;
}
class AdditionalDetails{
AdditionalDetails(this.start, this.end, this.month);
String start;
String end;
String month;
}
And I have a handler in which I am creating objects of AdditionalDetails and pushing into a list.
List<Employee> list = new List<Employee>;
String add1 = AdditionalDetails("start1", "end1", "dec").toString();
String add2 = AdditionalDetails("start2", "end2", "jan").toString();
list.add(1, add1);
list.add(2, add2);
I am displaying these items in a list and on click of each item , I have to display other details in a dialog box.
I am able to get the uuid by iterating over the list but when doing json.decode(additional_details), it is giving this:
SyntaxError: Unexpected token I in JSON at position 0
How can I get the start, end and month properties from the additionalDetails?
I think this is what you want.
class Employee {
Employee(this.uuid, this.additionalDetails);
String uuid;
String additionalDetails;
}
class AdditionalDetails {
AdditionalDetails(
this.start,
this.end,
this.month,
);
final String start;
final String end;
final String month;
#override
String toString() => '$start $end $month';
}
final list = <Employee>[];
final add1 = AdditionalDetails("start1", "end1", "dec").toString();
final add2 = AdditionalDetails("start2", "end2", "jan").toString();
list.add(Employee('1', add1));
list.add(Employee('2', add2));
More cool way:
class Employee {
Employee({
#required this.uuid,
#required this.additionalDetails,
});
final String uuid;
final AdditionalDetails additionalDetails;
factory Employee.fromJson(Map<String, dynamic> json) => Employee(
uuid: json["uuid"],
additionalDetails: json["additionalDetails"],
);
Map<String, dynamic> toJson() => {
"uuid": uuid,
"additionalDetails": additionalDetails.toJson(),
};
}
class AdditionalDetails {
AdditionalDetails({
#required this.start,
#required this.end,
#required this.month,
});
final String start;
final String end;
final String month;
factory AdditionalDetails.fromJson(Map<String, dynamic> json) =>
AdditionalDetails(
start: json["start"],
end: json["end"],
month: json["month"],
);
Map<String, dynamic> toJson() => {
"start": start,
"end": end,
"month": month,
};
}
final list = <Employee>[];
final add1 = AdditionalDetails(start: "start1", end: "end1", month: "dec");
list.add(Employee(uuid: '1', additionalDetails: add1));
final json = add1.toJson(); // Map<String, dynamic>
final startFromJson = json['start'];
final object = AdditionalDetails.fromJson(json); // AdditionalDetails
final startFromObject = object.start;
if you want to create an object out of string instead of jsondecode you should use toJson and fromJson function:
class AdditionalDetails{
AdditionalDetails(this.start, this.end, this.month);
String start;
String end;
String month;
AdditionalDetails.fromJson(Map<String, dynamic> json){
this.start = json['start'];
this.end = json['end'];
this.month = json['month'];
}
Map<String, dynamic> toJson(){
Map<String, dynamic> data = {};
data['start'] = this.start;
data['end'] = this.end;
data['month'] = this.month;
return data;
}
}
List<Employee> list = new List<Employee>;
String add1 = AdditionalDetails("start1", "end1", "dec").toJson();
String add2 = AdditionalDetails("start2", "end2", "jan").toJson();
list.add(1, add1);
list.add(2, add2);
final object = AdditionalDetails.fromJson(add1);
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>();