Flutter firebase Getx shopping cart: How do I increase the quantity of items without getting duplicates? - flutter

So right now I'm building a shopping cart using GetX and firebase. I'm trying to write the data to firebase if the user taps add to cart but not allow duplicate entries just increase the quantity #. Right now I'm getting duplicate entries.
class CartController extends GetxController {
static CartController instance = Get.find();
//cart controller for the shopping cart
Rx<double> totalCartPrice = 0.0.obs;
RxList<CartItemModel> products = RxList<CartItemModel>([]);
#override
void onReady() {
super.onReady();
ever(logController.userModel, editTotalPrice);
}
void addToCart(ProductModel product) {
try {
if (_isItemAlreadyAdded(product)) {
Get.snackbar("Check your cart", "${product.name} is already added");
} else {
String itemID = Uuid().v1();
logController.updateUserData({
"cart": FieldValue.arrayUnion([
{
"id": itemID,
"productId": product.id,
// "name": product.name,
"quantity": 1,
"price": product.price,
"image": product.image,
"cost": product.price,
}
])
});
Get.snackbar("Item added", "${product.name} was added to your cart");
}
} catch (e) {
Get.snackbar("Whoops...Cannot add this right now!",
"There was an error adding to cart",
duration: Duration(seconds: 3), backgroundColor: Colors.pinkAccent);
debugPrint(e.toString());
}
}
void deductCartItem(CartItemModel cartItem) {
try {
logController.updateUserData({
"cart": FieldValue.arrayRemove([cartItem.toJson()])
});
} catch (e) {
Get.snackbar("Error", "Cannot remove this item");
debugPrint(e.toString());
}
}
editTotalPrice(LoginUserModel usrModel) {
if (usrModel.cart!.isEmpty) {
print("Cart empty!");
} else if (usrModel.cart!.isNotEmpty) {
totalCartPrice.value = 50;
print("hi");
usrModel.cart!.forEach((cartItem) {
totalCartPrice.value += cartItem.cost!;
});
}
}
bool _isItemAlreadyAdded(ProductModel product) =>
logController.userModel.value.cart!
.where((item) => item.name == product.name)
.isNotEmpty;
void decreaseQuantity(CartItemModel item) {
if (item.quantity == 1) {
deductCartItem(item);
} else {
deductCartItem(item);
item.quantity! - 1;
logController.updateUserData({
"cart": FieldValue.arrayUnion([item.toJson()])
});
}
}
void increaseQuantity(CartItemModel item) {
deductCartItem(item);
item.quantity! + 1;
logger.i({"quantity": item.quantity});
logController.updateUserData({
"cart": FieldValue.arrayUnion([item.toJson()])
});
}
}
and here is my class:
class CartItemModel {
CartItemModel(
{this.productId,
this.id,
this.image,
this.name,
this.quantity,
required this.price,
this.cost});
CartItemModel.fromMap(Map<String, dynamic> data) {
id = data[ID];
image = data[IMAGE];
name = data[NAME];
quantity = data[QUANTITY];
cost = data[COST].toDouble();
productId = data[PRODUCT_ID];
price = data[PRICE];
}
static const COST = "cost";
static const ID = "id";
static const IMAGE = "image";
static const NAME = "name";
static const PRICE = "price";
static const PRODUCT_ID = "productId";
static const QUANTITY = "quantity";
double? cost;
String? id;
String? image;
String? name;
double? price;
String? productId;
int? quantity;
Map toJson() => {
ID: id,
PRODUCT_ID: productId,
IMAGE: image,
NAME: name,
QUANTITY: quantity,
COST: price! * quantity!,
PRICE: price
};
}
and because this is tied into the login session here is my login class:
class LoginUserModel {
String? displayName;
String? email;
String? photoUrl;
String? uid;
List<CartItemModel>? cart;
LoginUserModel(
{this.displayName, this.email, this.photoUrl, this.uid, this.cart});
LoginUserModel.fromSnapshot(DocumentSnapshot<Map<String, dynamic>> snapshot) {
displayName = snapshot.data()!["DISPLAYNAME"];
photoUrl = snapshot.data()!["PHOTOURL"];
email = snapshot.data()!["EMAIL"];
uid = snapshot.data()!["UID"];
cart = _convertCartItems(snapshot.data()!["CART"] ?? []);
}
List<CartItemModel> _convertCartItems(List cartFomDb) {
List<CartItemModel> _result = [];
if (cartFomDb.length > 0) {
cartFomDb.forEach((element) {
_result.add(CartItemModel.fromMap(element));
});
}
return _result;
}
List cartItemsToJson() => cart!.map((item) => item.toJson()).toList();
}
And my login controller:
class LoginController extends GetxController {
static LoginController instance = Get.find();
Rxn<User> fbUser = Rxn<User>();
final googleSignIn = GoogleSignIn();
RxBool isLoggedIn = false.obs;
Rx<LoginUserModel> userModel = LoginUserModel().obs;
String usersCollection = "users";
// Rx<UserModel> usrModel = UserModel().obs;
GoogleSignInAccount? _googleAcc;
LoginUserModel? _userModel;
#override
void onReady() {
super.onReady();
fbUser = Rxn<User>(auth.currentUser);
fbUser.bindStream(auth.userChanges());
ever(fbUser, setInitialScreen);
}
LoginUserModel? get loggedInUserModel => _userModel;
setInitialScreen(User? user) {
if (user == null) {
print("going to login page...");
Get.offAll(() => LoginPage());
} else {
print("The user is ${user.displayName}");
userModel.bindStream(listenToUser());
Get.offAll(() => AppSetup());
}
}
void googleLogin() async {
final googleUser = await googleSignIn.signIn();
if (googleUser == null) return;
_googleAcc = googleUser;
final googleAuth = await googleUser.authentication;
final cred = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
try {
await auth.signInWithCredential(cred).then((res) async {
print('Signed in successfully as ' + res.user!.displayName.toString());
print('email: ' + res.user!.email.toString());
LoginUserModel _newUser = LoginUserModel(
uid: res.user!.uid,
email: res.user!.email!,
displayName: res.user!.displayName,
photoUrl: res.user!.photoURL,
cart: [],
);
_addUserToFB(_newUser, res.user!);
});
} catch (e) {
debugPrint(e.toString());
Get.snackbar("Sign In Failed", "Try again");
}
}
// void signUp() async {
// try {
// await auth
// .createUserWithEmailAndPassword(
// email: email.text.trim(), password: password.text.trim())
// .then((result) {
// String _userId = result.user.uid;
// _addUserToFirestore(_userId);
// _clearControllers();
// });
// } catch (e) {
// debugPrint(e.toString());
// Get.snackbar("Sign In Failed", "Try again");
// }
// }
void signOut() async {
googleSignIn.signOut();
auth.signOut();
}
//maybe add clear controllers method?
updateUserData(Map<String, dynamic> data) {
logger.i("UPDATED");
firebaseFirestore
.collection(usersCollection)
.doc(fbUser.value?.uid)
.update(data);
}
Stream<LoginUserModel> listenToUser() => firebaseFirestore
.collection(usersCollection)
.doc(fbUser.value!.uid)
.snapshots()
.map((snapshot) => LoginUserModel.fromSnapshot(snapshot));
_addUserToFB(LoginUserModel usr, User firebaseUser) {
firebaseFirestore.collection(usersCollection).doc(usr.uid).set({
"displayName": usr.displayName,
"id": usr.uid,
"photoURL": usr.photoUrl,
"email": usr.email,
"cart": usr.cart
});
}
}
My firebase database is pictured below. The cart is in a subcategory (array) as I have it tied to the user who is logged in:

It looks like the issue is in your arrayUnion call because you are adding a new entry to the shopping cart array. There is perhaps an expectation that the method will find and update the provided object in the array.
What you would need to do is to find and replace/update the cart item in your local user object array and make a document update back to Firestore.
But instead of doing that, I'd like to suggest something you could consider: you might want to consider making the shopping cart a subcollection instead.
For two reasons
You have an unbound growing data-set (shopping cart items). That is making a good candidate for being a collection of its own.
You want to be able to update field values in individual documents (shopping cart items) without causing too much other "noise" in your app. When you store the shopping cart in your user object and update items in the array, you are also causing any listener that is subscribing to your user object to trigger a new read from the database.
Implementing your shopping cart as a sub collection allows for you to do this instead
Future<void> increaseQuantity(CartItemModel item) {
return FirebaseFirestore.instance
.collection("users")
.doc(userId)
.collection("cart")
.doc(item.id)
.update({"quantity": FieldValue.increment(1)});
}
You would do the same for decreaseQuantity and update quantity with FieldValue.increment(-1) instead.

Related

flutter firebase login/ auth: Getting too many writes?

I think I am getting too many writes to firebase as this is counting every login, or at least it's not preventing write cycles if the user already exists. I need to know how to do that. I am using flutter getx. Here is my login controller:
class LoginController extends GetxController {
static LoginController instance = Get.find();
Rxn<User> fbUser = Rxn<User>();
final googleSignIn = GoogleSignIn();
RxBool isLoggedIn = false.obs;
Rx<UserModel> userModel = UserModel().obs;
String usersCollection = "coffeeusers";
// Rx<UserModel> usrModel = UserModel().obs;
GoogleSignInAccount? _googleAcc;
UserModel? _userModel;
#override
void onReady() {
super.onReady();
fbUser = Rxn<User>(auth.currentUser);
fbUser.bindStream(auth.userChanges());
ever(fbUser, setInitialScreen);
}
UserModel? get loggedInUserModel => _userModel;
setInitialScreen(User? user) {
if (user == null) {
print("going to login page...");
Get.offAll(() => LoginPage());
} else {
print("The user is ${user.displayName}");
userModel.bindStream(listenToUser());
Get.offAll(() => AppSetup());
}
}
void googleLogin() async {
final googleUser = await googleSignIn.signIn();
if (googleUser == null) return;
_googleAcc = googleUser;
final googleAuth = await googleUser.authentication;
final cred = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
try {
await auth.signInWithCredential(cred).then((res) async {
print('Signed in successfully as ' + res.user!.displayName.toString());
print('email: ' + res.user!.email.toString());
UserModel _newUser = UserModel(
id: res.user!.uid,
email: res.user!.email!,
name: res.user!.displayName,
photoURL: res.user!.photoURL,
cart: [],
);
_addUserToFB(_newUser, res.user!);
});
} catch (e) {
debugPrint(e.toString());
Get.snackbar("Sign In Failed", "Try again");
}
}
// void signUp() async {
// try {
// await auth
// .createUserWithEmailAndPassword(
// email: email.text.trim(), password: password.text.trim())
// .then((result) {
// String _userId = result.user.uid;
// _addUserToFirestore(_userId);
// _clearControllers();
// });
// } catch (e) {
// debugPrint(e.toString());
// Get.snackbar("Sign In Failed", "Try again");
// }
// }
void signOut() async {
googleSignIn.signOut();
auth.signOut();
}
//maybe add clear controllers method?
updateUserData(Map<String, dynamic> data) {
logger.i("UPDATED");
firebaseFirestore
.collection(usersCollection)
.doc(fbUser.value?.uid)
.update(data);
}
Stream<UserModel> listenToUser() => firebaseFirestore
.collection(usersCollection)
.doc(fbUser.value!.uid)
.snapshots()
.map((snapshot) => UserModel.fromSnapshot(snapshot));
_addUserToFB(UserModel usr, User firebaseUser) {
firebaseFirestore.collection(usersCollection).doc(usr.id).set({
"displayName": usr.name,
"id": usr.id,
"photoURL": usr.photoURL,
"email": usr.email,
"cart": usr.cart
});
}
}
And here is my login user model:
class UserModel {
static const ID = "id";
static const NAME = "name";
static const EMAIL = "email";
static const CART = "cart";
static const PHOTOURL = "photoURL";
static const REVIEWS = "reviews";
String? id;
String? name;
String? email;
String? photoURL;
List<CartItemModel>? cart;
List<CartItemModel>? reviews;
UserModel({
this.id,
this.photoURL,
this.email,
this.name,
this.cart,
this.reviews,
});
UserModel.fromSnapshot(DocumentSnapshot<Map<String, dynamic>> snapshot) {
name = snapshot.data()?['NAME'] ?? '';
email = snapshot.data()?['EMAIL'] ?? '';
photoURL = snapshot.data()?['PHOTOURL'] ?? '';
id = snapshot.data()?['ID'] ?? '';
cart = _convertCartItems(snapshot.data()?['CART'] ?? []);
}
List<CartItemModel> _convertCartItems(List cartFomDb) {
List<CartItemModel> result = [];
if (cartFomDb.isNotEmpty) {
for (var element in cartFomDb) {
result.add(CartItemModel.fromMap(element));
}
}
return result;
}
List cartItemsToJson() => cart!.map((item) => item.toJson()).toList();
Map<String, dynamic> toJson() => {
"uid": id,
"email": email,
"name": name,
"photoUrl": photoURL,
"cart": cart,
"reviews": reviews,
};
}
I know I also need to fix this so that the user can add a review of the place. The reviews will essentially be a sub list. All this has to be specific to the user, at least the editing potential. I want other people to be able to read the reviews etc. But for now I need to work on reducing my writes

How to get Single document from firestore and call the fields in UI in flutter/dart

Here is my attempt
In my Controller I have this
class UserController extends GetxController {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
var _proo;
get prooo => _proo;
Future<Member?> readProfile() async {
_proo = FireStoreHelper().fFetch("users", "user1");
}
}
In my FireStoreHelper I have this
class FireStoreHelper {
fFetch(collection, doc) {
final docMember =
FirebaseFirestore.instance.collection(collection).doc(doc);
var query = docMember.get();
return query;
}
This is my Model
class Member {
final String? username;
//...others
Member({
this.username,
//...others
});
static Member fromJson(Map<String, dynamic> json) => Member(
username: json['username'],
//...others
);
}
Then in my UI I have this
Get.lazyPut(() => UserController().readProfile());
return GetBuilder<UserController>(builder: (userController) {
//.......
Text(userController.prooo.username),
}
Actually what am trying get a username of user1 as seen in the Image below
Please help me, I am new to this.
try this one...
fFetch(collection, doc) async {
final docMember = await
FirebaseFirestore.instance.collection(collection).doc(doc).get();
return docMember;
}
static Future<Member?> readProfile() async {
_proo = await FireStoreHelper().fFetch("users", "user1");
Member member = Member.fromJson(_proo);
return member;
}

Flutter - user model is NULL even after binding it using bindStream

I am trying to add a shopping cart functionality to my app wherein the UserModel contains fields name,email,uid and cart. I have created an AuthController extends GetxController where I have created userModel isntance and then in setInitialScreen function I am binding the userModel to a function "listenToUser()" which is a Stream and recieves snapshot from firestore and maps it to the userModel. But on printing the userModel I see null being printed in the console meaning the data is not getting binded which is causing problems as i can't access the cart stored in the userModel.
Edit: I saw that I need to attach obs to userModel like: Rx<model.User>? userModel = model.User().obs; but there's a problem that all the fields in this model are required and how can i pass these field values when they have not yet been intialized.
Console output:
AuthController code
class AuthController extends GetxController {
static AuthController instance = Get.find();
late Rx<User?> _user;
Rx<model.User>? userModel;
#override
void onReady() {
super.onReady();
_user = Rx<User?>(firebaseAuth.currentUser);
_user.bindStream(firebaseAuth.authStateChanges());
ever(_user, _setInitialScreen);
}
_setInitialScreen(User? user) {
if (user == null) {
Get.offAll(() => LoginScreen());
} else {
userModel?.bindStream(listenToUser());
Get.offAll(() => const HomeScreen());
print(userModel); // PRINTING USER MODEL TO SEE IF ITS NULL
// userModel?.bindStream(listenToUser());
}
}
// registering the user
void registerUser(String username, String email, String password) async {
try {
if (username.isNotEmpty && email.isNotEmpty && password.isNotEmpty) {
// save our user to our auth and firebase firestore
UserCredential cred = await firebaseAuth.createUserWithEmailAndPassword(
email: email,
password: password,
);
model.User user = model.User(
name: username, email: email, uid: cred.user!.uid, cart: []);
await firestore
.collection('users')
.doc(cred.user!.uid)
.set(user.toJson());
} else {
Get.snackbar(
'Error Creating Account',
'Please enter all the fields',
);
}
} catch (e) {
Get.snackbar(
'Error Creating Account',
e.toString(),
);
}
}
void loginUser(String email, String password) async {
try {
if (email.isNotEmpty && password.isNotEmpty) {
await firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
print('log success');
} else {
Get.snackbar(
'Error Logging in',
'Please enter all the fields',
);
}
} catch (e) {
Get.snackbar(
'Error Logging in',
e.toString(),
);
}
}
updateUserData(Map<String, dynamic> data) {
print("UPDATED");
firestore.collection('users').doc(_user.value?.uid).update(data);
}
Stream<model.User> listenToUser() => firestore
.collection('users')
.doc(_user.value?.uid)
.snapshots()
.map((snapshot) => model.User.fromSnap(snapshot));
}
User Model code:
class User {
// static const UID = "uid";
// static const NAME = "name";
// static const EMAIL = "email";
String uid;
String name;
String email;
List<CartItemModel> cart;
User(
{required this.name,
required this.email,
required this.uid,
required this.cart});
Map<String, dynamic> toJson() =>
{"name": name, "email": email, "uid": uid, "cart": cart};
// static User fromSnap(DocumentSnapshot snap) {
static User fromSnap(DocumentSnapshot snap) {
var snapshot = snap.data() as Map<String, dynamic>;
return User(
name: snapshot['name'],
email: snapshot['email'],
uid: snapshot['uid'],
cart: _convertCartItems(snapshot['cart'] ?? []));
}
// List<CartItemModel> _convertCartItems(List cartFromDb) {
static List<CartItemModel> _convertCartItems(List cartFromDb) {
List<CartItemModel> _result = [];
// logger.i(cartFromDb.lengt);
print(cartFromDb.length);
cartFromDb.forEach((element) {
_result.add(CartItemModel.fromMap(element));
});
return _result;
}
}
Also I referred this github for shopping cart functionality but I have made some changes to make it null safe: cart functionality github
Use Rxn<T>() for nullable rx:
final _user = Rxn<User>();
Then on onInit():
_user.bindStream(firebaseAuth.authStateChanges());

flutter - how to pass required parameters when they have not yet been initialized

I am creating a userModel instance inside my authController and want to add obs from Getx to that userModel like: Rx<model.User>? userModel = model.User().obs;, but the fields inside my model.User are all required.
How can I pass these parameters if they have not yet been initialized as they will get initialized after the user signs in?
I referred this github: Github where he has done it because his parameters are not "required" as it is old, but now flutter is null safe and is forcing "required" parameters in my user model.
AuthController code:
class AuthController extends GetxController {
static AuthController instance = Get.find();
late Rx<User?> _user;
// Rx<model.User>? userModel;
Rx<model.User>? userModel = model.User().obs; //ERROR CAUSING LINE**
#override
void onReady() {
super.onReady();
_user = Rx<User?>(firebaseAuth.currentUser);
_user.bindStream(firebaseAuth.authStateChanges());
ever(_user, _setInitialScreen);
}
_setInitialScreen(User? user) {
if (user == null) {
Get.offAll(() => LoginScreen());
} else {
// userModel?.bindStream(listenToUser());
Get.offAll(() => const HomeScreen());
userModel?.bindStream(listenToUser());
print(userModel);
}
}
// registering the user
void registerUser(String username, String email, String password) async {
try {
if (username.isNotEmpty && email.isNotEmpty && password.isNotEmpty) {
// save our user to our auth and firebase firestore
UserCredential cred = await firebaseAuth.createUserWithEmailAndPassword(
email: email,
password: password,
);
model.User user = model.User(
name: username, email: email, uid: cred.user!.uid, cart: []);
await firestore
.collection('users')
.doc(cred.user!.uid)
.set(user.toJson());
} else {
Get.snackbar(
'Error Creating Account',
'Please enter all the fields',
);
}
} catch (e) {
Get.snackbar(
'Error Creating Account',
e.toString(),
);
}
}
void loginUser(String email, String password) async {
try {
if (email.isNotEmpty && password.isNotEmpty) {
await firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
print('log success');
} else {
Get.snackbar(
'Error Logging in',
'Please enter all the fields',
);
}
} catch (e) {
Get.snackbar(
'Error Logging in',
e.toString(),
);
}
}
updateUserData(Map<String, dynamic> data) {
print("UPDATED");
firestore.collection('users').doc(_user.value?.uid).update(data);
}
Stream<model.User> listenToUser() => firestore
.collection('users')
.doc(_user.value?.uid)
.snapshots()
.map((snapshot) => model.User.fromSnap(snapshot));
}
User model code:
class User {
// static const UID = "uid";
// static const NAME = "name";
// static const EMAIL = "email";
String uid;
String name;
String email;
List<CartItemModel> cart;
User(
{required this.name,
required this.email,
required this.uid,
required this.cart});
Map<String, dynamic> toJson() =>
{"name": name, "email": email, "uid": uid, "cart": cart};
// static User fromSnap(DocumentSnapshot snap) {
static User fromSnap(DocumentSnapshot snap) {
var snapshot = snap.data() as Map<String, dynamic>;
return User(
name: snapshot['name'],
email: snapshot['email'],
uid: snapshot['uid'],
cart: _convertCartItems(snapshot['cart'] ?? []));
}
// List<CartItemModel> _convertCartItems(List cartFromDb) {
static List<CartItemModel> _convertCartItems(List cartFromDb) {
List<CartItemModel> _result = [];
// logger.i(cartFromDb.lengt);
print(cartFromDb.length);
cartFromDb.forEach((element) {
_result.add(CartItemModel.fromMap(element));
});
return _result;
}
}
Add ? operator to tell explicity that the object can be null.
So the code goes like:
class User {
String? uid;
String? name;
String? email;
List<CartItemModel>? cart;
}

Data gets lost when added to a Model

I am getting data from Firebase Database and Adding it to a List of my Model class. I tested the incoming data by printing to Console and it works fine, but once i add the data to my model class, it disappears.
Here's my Provider class where i'm loading the data.
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:local_stuffs_notification/apis/fcm.dart';
import 'package:local_stuffs_notification/models/request_model.dart';
import 'package:shared_preferences/shared_preferences.dart';
class IncomingRequest with ChangeNotifier {
List<RequestModel> _incomingRequests = [];
IncomingRequest(this._incomingRequests);
List<RequestModel> get incomingRequest {
return [..._incomingRequests];
}
Future<void> setIncomingRequest(RequestModel requestModel) async {
try {
DatabaseReference reference =
FirebaseDatabase.instance.ref("incomingRequests");
reference.child(requestModel.id).child(Fcm.getUid()).set(
{
"name": requestModel.name.toString(),
"phone": requestModel.phone.toString(),
"email": requestModel.email.toString(),
"fcmToken": requestModel.fcmToken.toString(),
},
);
notifyListeners();
} catch (error) {
rethrow;
}
}
Future<void> loadIncomingRequests() async {
try {
SharedPreferences preferences = await SharedPreferences.getInstance();
DatabaseReference reference = FirebaseDatabase.instance
.ref('incomingRequests/${preferences.getString('userId')!}');
Stream<DatabaseEvent> stream = reference.onValue;
stream.listen((DatabaseEvent event) {
print(event.snapshot.value);
final data = event.snapshot.value as Map;
print('data: $data');
final List<RequestModel> loadedRequest = [];
data.forEach(
(key, value) {
print('requestData: ${value['name']}');
loadedRequest.add(
RequestModel(
id: key.toString(),
name: value['name'].toString(),
fcmToken: value['fcmToken'].toString(),
phone: value['phone'].toString(),
email: value['email'].toString(),
),
);
print(loadedRequest);
},
);
_incomingRequests = loadedRequest;
print('LoadedRequests: $loadedRequest');
notifyListeners();
});
// reference.onValue.listen(
// (event) {
// if (event.snapshot.value == null) {
// return;
// }
// final data = event.snapshot.value as Map;
// final List<RequestModel> loadedRequests = [];
// data.forEach(
// (key, requestData) {
// loadedRequests.add(
// RequestModel(
// id: key,
// name: requestData['name'],
// fcmToken: requestData['fcmToken'],
// phone: requestData['phone'],
// email: requestData['email'],
// ),
// );
// },
// );
// _incomingRequests = loadedRequests;
// notifyListeners();
// },
//);
} catch (error) {
rethrow;
}
}
}
Here's my Model Class
class RequestModel {
final String id;
final String name;
final String fcmToken;
final String phone;
final String email;
RequestModel({
required this.id,
required this.name,
required this.fcmToken,
required this.phone,
required this.email,
});
}
I'm getting the data until i added it to loadedRequest List
Please help, i've spent hours on this and i don't know what i'm doing wrong. When i print the loadedRequest list, i get an empty list. Thanks.
Those logs aren't showing an empty list - It says [Instance of 'RequestModel']. That means there is a value there, but Dart simply doesn't know how to convert RequestModel to a String so that it can be printed out on the console.
An empty list would be printed simply as [], and if you had two values, for example, you would see [Instance of 'RequestModel', Instance of 'RequestModel'].
To print out your values with more detail, you can override the toString() method on your class.
For example:
class RequestModel {
final String id;
final String name;
final String fcmToken;
final String phone;
final String email;
RequestModel({
required this.id,
required this.name,
required this.fcmToken,
required this.phone,
required this.email,
});
#override
String toString() =>
"RequestModel(id: $id, name: $name, fcmToken: $fcmToken, phone: $phone, email: $email)";
}
take a look at the raw data once again, it contains all the users data so you need to get the access the uid before the name
final uid = FirebaseAuth.instance.currentUser!.uid;
and then for the RequestModel:
name: data[uid]['name']