Flutter SQFlite Class to Json() - flutter

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

Related

How to access token saved as a variable in different dart page in a secured storage

I have saved a token as a variable in flutter secure storage in a file called login_response_model.dart and I am trying to access it in the home screen, but I keep getting error as undefined name:
Here is the login_response_model.dart:
class LoginResponse {
dynamic? key;
List<dynamic>? non_field_errors;
LoginResponse({this.key, this.non_field_errors});
factory LoginResponse.fromJson(mapOfBody) {
return LoginResponse(
key: mapOfBody['key'],
non_field_errors: mapOfBody['non_field_errors'],
);
}
}
LoginResponseModel loginResponseJson(String str) =>
LoginResponseModel.fromJson(json.decode(str));
class LoginResponseModel {
dynamic? key;
List<dynamic>? non_field_errors;
LoginResponseModel({this.key, this.non_field_errors});
LoginResponseModel.fromJson(mapOfBody) {
key:
mapOfBody['key'];
non_field_errors:
mapOfBody['non_field_errors'];
print(mapOfBody['key']);
// Create storage
final storage = new FlutterSecureStorage();
// Write value
storage.write(key: 'Token', value: mapOfBody['key']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['key'] = key;
_data['non_field_errors'] = non_field_errors;
return _data;
}
}
class Data {
Data({
required this.username,
required this.email,
required this.date,
required this.id,
required this.key,
});
late final String username;
late final String email;
late final String date;
late final String id;
late final String key;
Data.fromJson(Map<String, dynamic> json) {
username = json['username'];
email = json['email'];
date = json['date'];
id = json['id'];
key = json['key'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['username'] = username;
_data['email'] = email;
_data['date'] = date;
_data['id'] = id;
_data['key'] = key;
return _data;
}
}
Here is the homescreen:
Future<User> fetchUser() async {
var url = Uri.parse(Config.apiURL + Config.userProfileAPI);
var value = storage.read(key: 'Token');
My question:
How can I access the token saved in a secured storage into the home screen?
Is there an easier and more secure way to access the token saved other than the way I have arranged it?
Use can you SharedPreference & save token here. Each time you want to use, you just need to:
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString("key_token") ?? "";
However, each time you want to use it, you again need to use async function & wait until it give you saved token. Although it doesn't take so much time & space but we need to notice this. You can init a global variable to save token whenever open app or login success. Learn more about Singleton.
Example in my app: data_instance.dart
class DataInstance {
static DataInstance _instance = new DataInstance.internal();
DataInstance.internal();
factory DataInstance() => _instance;
late String accessToken;
initPreference() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
DataInstance().accessToken = prefs.getString("key_token_haha")?? '';
}
}
In main.dart:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await DataInstance().initPreference();
runApp(const MyApp());
}

Flutter Firestore - retrieve data from user document and insert in post model

I have two models User and Post which are as follows
class UserModel {
final String id;
final String name;
final String email;
final String bio;
final String createdAt;
UserModel(this.id, this.name, this.email, this.bio, this.createdAt);
}
class PostModel {
final String id;
final UserModel postedBy;
final String content;
final String createdAt;
PostModel(this.id, this.postedBy, this.content, this.createdAt);
}
In firestore I am storing only uid of post creator as string field "postedBy" not entire UserModel and now the goal is to get all the details of a post such as post id, content, createdAt and everything which is in user model as a stream. Below is the code
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_crud/models/post.dart';
import 'package:flutter_crud/models/user.dart';
class DatabaseService {
final uid = FirebaseAuth.instance.currentUser!.uid;
final userCollection = FirebaseFirestore.instance.collection('users');
final postCollection = FirebaseFirestore.instance.collection('posts');
Stream<List<PostModel?>> get getPostData {
return postCollection.snapshots().map((QuerySnapshot querySnapshot) =>
querySnapshot.docs.map((DocumentSnapshot snapshot) {
final data = snapshot.data() as dynamic;
print('1 - DATA ****** ${data['content']}'); // this print works
userCollection.doc(uid).snapshots().map((DocumentSnapshot doc) {
final userData = doc.data() as dynamic;
final userInfo = UserModel(
doc.id,
userData['name'],
userData['email'],
userData['bio'],
userData['createdAt'].toDate().toString());
print('2 - USER INFO ****** $userInfo'); // doesnt print anything
return PostModel(
snapshot.id, userInfo, data['content'], data['createdAt']);
});
}).toList());
}
}
in main.dart I am registering the provider as:
StreamProvider<List<PostModel?>>(
create: (ctx) => DatabaseService().getPostData, initialData: []),
and within build widget of the file I would like to use data
final posts = Provider.of<List<PostModel?>>(context);
print('********LENGTH********: ${posts.length}'); // print 0 as length
how to fix the getter getPostData?

List from Model class is not storing in the new list in the controller class

**Product Modelclass which extracted from json file**
class Product {
int? _totalSize;
int? _typeId;
int? _offset;
late List<ProductModel> _products;
List<ProductModel> get products=> _products;
Product({required totalSize, required typeId, required offset, required products}){
this. _totalSize=totalSize;
this. _typeId=typeId;
this. _offset=offset;
this. _products=products;
}
Product.fromJson(Map<String, dynamic> json) {
_totalSize = json['total_size'];
_typeId = json['type_id'];
_offset = json['offset'];
if (json['productModel'] != null) {
_products= <ProductModel>[];
json['products'].forEach((v) {
_products.add(new ProductModel.fromJson(v));
});
}
}
}
class ProductModel {
int? id;
String? name;
String? description;
int? price;
int? stars;
String? img;
String? location;
String? createdAt;
String? updatedAt;
int? typeId;
ProductModel(
{this.id,
this.name,
this.description,
this.price,
this.stars,
this.img,
this.location,
this.createdAt,
this.updatedAt,
this.typeId});
ProductModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
description = json['description'];
price = json['price'];
stars = json['stars'];
img = json['img'];
location = json['location'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
typeId = json['type_id'];
}
}
This is my Api_client class extending Getx to get response from server
import 'package:get/get.dart';
class Api_client extends GetConnect{
late String token;
late String AppbaseUrl;
late Map<String,String> _mainHeader;
Api_client({required this.AppbaseUrl}){
baseUrl=AppbaseUrl;
timeout=Duration(seconds: 30);
token="";
_mainHeader={
'Content-type':' application/json; charset-UTF-8',
'Authorization':' Bearer $token',
};
}
Future <Response> getData(String uri) async{
try{
Response response = await get(uri);
return response;
}catch(e){
return Response(statusCode: 1,statusText: e.toString());
}
}
}
**This is Popular_Product_List_Repo class extending Getx
getservices to get response from Api_client**
import 'package:get/get.dart';
import 'package:untitled/data/api/Api_client.dart';
class Popular_Product_List_Repo extends GetxService{
final Api_client apiClient;
Popular_Product_List_Repo({ required this.apiClient});
Future <Response> get_popular_product_list()async{
return await
apiClient.getData("/api/v1/products/popular");
}
}
This is my controller class Popular_Product_Controller which is responsible for to get response from Popular_Product_List_Repo and retrieve the list and store the list in my new created List which is List_Popular_product_list=[]; to show the list on my UI
import 'package:get/get.dart';
import 'package:untitled/data/Repository/Popular_Product_List_Repo.dart';
import 'package:untitled/data/models/Products_model.dart';
class Popular_Product_Controller extends GetxController{
final Popular_Product_List_Repo popular_product_repo ;
List<dynamic>_Popular_product_list=[];
Popular_Product_Controller({required this.popular_product_repo});
Future getPopular_Product_list() async{
Response response=await popular_product_repo.get_popular_product_list();
if(response.statusCode==200){
print("got products");
_Popular_product_list=[];
_Popular_product_list.addAll(Product.fromJson(response.body).products);
print(_Popular_product_list);
update();
}else{
}
}
}
Problem is I want to make sure that response from server is right and stored without any issue in my list _Popular_product_list which I created in the Popular_Product_Controller I wrote print statement which is got products and _Popular_product_list itself to check that data is inside the _Popular_product_list or not so whenever I run its not showing either any statements which means the function getPopular_Product_list() is not working as I expected so what is went wrong and why list products is not storing inside the _Popular_product_list ?
In order to verify if you are getting some data.. you can use the **Either** class in Dart which can imported from pub.dev. its make it easy to handle
for example,
final Either<String, List<Product>> result =
await getProductList();
result.fold((exception) {
CustomToast.showErrorToast(Messages.UNABLE_TO_LOAD_PRODUCT_LIST);
}, (products) async {
//get products here and you can do what you want
}

Is there a way to get Firestore data to User model class in flutter then pass the data to the screens?

There is a way to get firestore data for example " User information" into user model class in flutter?
This is my User Class:
class Users {
final int id;
final String firstName;
final String lastName;
final String emailAddress;
final String imageProfile;
const Users({
this.id,
this.firstName,
this.lastName,
this.emailAddress,
this.imageProfile,
});
}
final Users currentUser = Users(
id: 'GET_DATA_FROM_FIRESTORE'/// firebaseUSer.currentUserUID
firstName: 'GET_DATA_FROM_FIRESTORE',
lastName: 'GET_DATA_FROM_FIRESTORE',
emailAddress: 'GET_DATA_FROM_FIRESTORE',
imageProfile: 'GET_DATA_FROM_FIRESTORE',
);
then pass the data with currentUser.firstName etc.. to other widgets.
the data I need to retrieve into this class is created into SignuUp form in flutter and pushed to firestore collection
I used this in my project.I hope that will helpful.
Model Class
class Message{
String id;
String message;
String senderId;
Timestamp timeStamp;
bool isMedia;
Message({this.id,this.message,this.senderId,this.timeStamp,this.isMedia});
factory Message.fromSnapshot(DocumentSnapshot snapshot){
return Message(
id:snapshot.id,
message: snapshot.data()['message'],
senderId: snapshot.data()['senderId'],
timeStamp: snapshot.data()['timeStamp'],
isMedia: snapshot.data()['isMedia'],
);
}
Map<String, dynamic> toJson() =>
{
'message': message,
'senderId': senderId,
'isMedia': isMedia,
'timeStamp': DateTime.now(),
};
}
Service Class
*Initial
final FirebaseFirestore _fBaseFireStore = FirebaseFirestore.instance;
CollectionReference _collectionRef;
MessageService() {
_collectionRef = _fBaseFireStore.collection('Conversation');
}
*Get datas from firestore
Stream<List<Message>> getMessages(String conversationId) {
var ref = _collectionRef
.doc(conversationId)
.collection('messages');
return ref.snapshots().map(
(event) => event.docs.map((e) => Message.fromSnapshot(e)).toList());
}
*Write data to firestore
Future<void> sendMessage(Message message, String conversationId) async {
var ref = _collectionRef.doc(conversationId).collection('messages');
await ref.add(message.toJson());
}

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.