How to convert a String to Object in Flutter? - flutter

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);

Related

Flutter SQFlite Class to Json()

I am currently working on an app where the user is able to store data on their device locally. Therefor I am using the sqflite package but I am running into some errors converting my Class data into Json.
This is the error message I get:
A value of type 'Set' can't be returned from the method
'toJson' because it has a return type of 'Map<String, Widget>'.
due to this line:
Map<String, Widget> toJson() => {
EntryFields.id = id,
EntryFields.name = name,
EntryFields.navigation = navigation,
};
This is my class:
import 'package:flutter/material.dart';
const String tableFavs = 'favorites';
class EntryFields {
static late String id = '_id';
static late String name = '_name';
static late String navigation = '_navigation';
}
class Entries {
final int id;
final String name;
final Widget navigation;
Entries({
required this.id,
required this.name,
required this.navigation,
});
Map<String, Widget> toJson() => {
EntryFields.id = id,
EntryFields.name = name,
EntryFields.navigation = navigation,
};
}
and this is a snipped from my database:
Future<Entries> create(Entries entries) async {
final db = await instance.database;
final id = await db.insert(tableFavs, entries.toJson());
}
you can't store a widget in the database it should be Map<String, String>
try to store the parameters of the widget as a String, not the whole widget
you can store these types double, string, int, bool..
try using the below code
class EntryFields {
static late String id = '_id';
static late String name = '_name';
static late String navigation = '_navigation';
}
class Entries {
const Entries({
this.id,
this.name,
this.navigation,
});
final String? id;
final String? name;
final String? navigation;
Map<String, dynamic> toJson() => {
"_id": id,
"_name": name,
"_navigation": navigation,
};
}
Future<void> create(Entries entries) async {
final db = await instance.database;
final id = await db.insert(tableFavs, entries.toJson());
}
void main(){
final entriesFromField = Entries(
id: EntryFields.id,
name: EntryFields.name,
navigation: EntryFields.navigation
);
create(entriesFromField);
}
or better you can use this json generator

How to sort a DateTime list in Flutter

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

Dart - How do you multi level sort on a list<T>

I am trying to sort a list of List
I know you can sort by using _cartItems.sort((a, b) => a.code.compareTo(b.code)); but I am trying to sort by group then by code. More of a similar feature like MS Excel multi level sorting.
to hack this I tried this and it seemed to work fine on some cases, but still not very stable.
_cartItems.sort((a, b) => a.code.compareTo(b.code));
_cartItems.sort((a, b) => a.group.compareTo(b.group));
for example, in cases where there is only a single group, it will do weird things and sort 6,2,3,4,5, etc.
Any way to multi-sort?
class CartItems:
class CartItem {
String qty;
final String code;
final String desc;
final String invt;
final String codealt;
final String descalt;
final String group;
final String price;
final String disc1;
String globalPrice;
String total;
bool isSelected;
CartItem(
this.qty,
this.code,
this.desc,
this.invt,
this.codealt,
this.descalt,
this.group,
this.price,
this.disc1,
this.globalPrice,
this.total,
{this.isSelected = false});
CartItem.fromJson(Map<String, dynamic> json)
: qty = json['qty'],
code = json['code'],
desc = json['desc'],
invt = json['invt'],
codealt = json['codealt'],
descalt = json['descalt'],
group = json['group'],
price = json['price'],
disc1 = json['disc1'],
globalPrice = json['globalPrice'],
total = json['total'],
isSelected = false;
Map<String, dynamic> toJson() {
return {
"qty": this.qty,
"code": this.code,
"desc": this.desc,
"invt": this.invt,
"codealt": this.codealt,
"descalt": this.descalt,
"group": this.group,
"price": this.price,
"disc1": this.disc1,
"globalPrice": this.globalPrice,
"total": this.total,
};
}
///get function to get the properties of Item
dynamic get(String propertyName) {
var _mapRep = toJson();
if (_mapRep.containsKey(propertyName)) {
return _mapRep[propertyName];
}
throw ArgumentError('propery not found');
}
}
for the example data please check https://justpaste.it/1v8t8
Implement the comparable interface for CartItem then in the compareTo function, you can check all the parameters that you want to sort by:
void main() {
List<CartItem> cartItems = [...];
cartItems.sort();
}
class CartItem implements Comparable<CartItem>{
String qty;
final String code;
final String desc;
final String invt;
final String codealt;
final String descalt;
final String group;
final String price;
final String disc1;
String globalPrice;
String total;
bool isSelected;
CartItem(
this.qty,
this.code,
this.desc,
this.invt,
this.codealt,
this.descalt,
this.group,
this.price,
this.disc1,
this.globalPrice,
this.total,
{this.isSelected = false});
factory CartItem.fromJson(Map<String, dynamic> json){
return CartItem(
json['qty'],
json['code'],
json['desc'],
json['invt'],
json['codealt'],
json['descalt'],
json['group'],
json['price'],
json['disc1'],
json['globalPrice'],
json['total'],
);
}
Map<String, dynamic> toJson() {
return {
"qty": this.qty,
"code": this.code,
"desc": this.desc,
"invt": this.invt,
"codealt": this.codealt,
"descalt": this.descalt,
"group": this.group,
"price": this.price,
"disc1": this.disc1,
"globalPrice": this.globalPrice,
"total": this.total,
};
}
///get function to get the properties of Item
dynamic get(String propertyName) {
var _mapRep = toJson();
if (_mapRep.containsKey(propertyName)) {
return _mapRep[propertyName];
}
throw ArgumentError('propery not found');
}
#override
int compareTo(CartItem other) {
// compare the groups
final gc = group.compareTo(other.group);
// if there are not equal gc will not be 0
if (gc != 0) return gc;
// if there are equal, then gc will be 0 so will go and compare codes
final cc = code.compareTo(other.code);
// return code compare result
return cc;
}
}
Another more functional way to archive this is like this:
void main() {
List<CartItem> cartItems = [...];
cartItems.sort((a, b) =>
<Comparator<CartItem>>[
(o1, o2) => o1.group.compareTo(o2.group),
(o1, o2) => o1.code.compareTo(o2.code),
// add more comparators here
].map((e) => e(a, b))
.firstWhere((e) => e != 0,
orElse: () => 0));
}

Flutter how to cast the model object to another model to save it to HIVE

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>();

Flutter Save Object on SharedPreferences

I have a working json parsing from my commerce API. all are working fine except for storing the add cart product to the shared preferences. How can I achieve this? I got an error of type
'ProductsModel' is not a subtype of type 'Map<String, dynamic>';
Here's my ProductsModel
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
);
}
}
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']);
}
}
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']
);
}
}
and I am testing to stored the ProductsModel only by using this function only
Here's my function
storedCart(products){
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('cart', products);
}
STEP 1 : Add a toMap() method in your class
Map<String,dynamic> toMap() {
var map = new Map<String, dynamic>();
map["id"] = id;
map["name"] = name;
map["description"] = description;
// Add all other fields
return map;
}
STEP 2 : While storing this in SharedPreferences call the toMap() method on the object
This will return a Map<String,dynamic> representation of your current object.
Map<String,dynamic> productsMap = products.toMap();
STEP 3 : Convert the object to String by using json.encode() and store it !
storedCart(productsMap){
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('cart', json.encode(productsMap));
}
Note :
Dont forget to import dart:convert
While retrieving the object don't forget to use json.decode()
If you are having trouble understanding why we used json.encode(), try printing the object before and after using the function, you'll notice that when we convert our object to JSON it becomes a big String, Therefore it is possible for us to store it in SharedPreferences using the "putString()" method.