How can I check this in collection? - firebase

I have added this collection:
Map<String, String> userDataMap = {
"userName": usernameEditingController.text,
"userEmail": emailEditingController.text,
"account": userType // there is premium and regular account type
};
...
Future<void> addUserInfo(userData) async {
Firestore.instance.collection("users").add(userData).catchError((e) {
print(e.toString());
});
}
And actually I don't know how to get info about account type, I would like to print/get value assigned to "account".
This is what I tried but it did nothing:
var ok = await Firestore.instance
.collection('users')
.where('email', isEqualTo: email)
.getDocuments();
print(ok);
Thank you in advance.

Inside the document, you have a field called userEmail and not email therefore you need to do the following:
var userDoc = await Firestore.instance
.collection('users')
.where('userEmail', isEqualTo: email)
.getDocuments();
userDoc.documents.forEach((result) {
print(result.data["account"]);
});

Related

Fetching user name returns null at first time with Flutter Firebase

I want to have the username (in Arabic) on the home page from firebase. When I ran the app the first time every time I turn on the emulator it returns null. But if I run it one more time/hot reload it is good.
I tried using toString() but it also did not work.
Here is my code:
//user's info
late User user;
final _auth = FirebaseAuth.instance;
late User signedInUser;
var sex;
var age;
var name;
Future<void> _getData() async {
FirebaseFirestore.instance
.collection('users')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
if (doc["email"] == signedInUser.email) {
name = doc['name'];
age = doc['age'];
sex = doc['sex'];
print(doc['name']); //might delete
}
});
});
}
Widget build(BuildContext context) {
return FutureBuilder(
future: _getData(),
builder: (context, snapshot) => snapshot.connectionState ==
ConnectionState.waiting
? //more code
Text(
'$name'.toString(),
style: TextStyle(
),
) ```
Since _getData is an asynchronous method, it needs to return a Future, or it can use await, but in your code it does neither of those things.
For example, this now uses await to ensure the method only completes once the name is set:
Future<void> _getData() async {
var querySnapshot = await FirebaseFirestore.instance
.collection('users')
.get();
querySnapshot.docs.forEach((doc) {
if (doc["email"] == signedInUser.email) {
name = doc['name'];
age = doc['age'];
sex = doc['sex'];
print(doc['name']); //might delete
}
});
}

How to add data from a subcollection in Firestore to a List?

FirebaseFirestore _firestore = FirebaseFirestore.instance;
CollectionReference _userRef = FirebaseFirestore.instance.collection('users');
Future getFriends() async {
List<Map> info = [];
await _firestore
.collection('friends')
.doc('lUb3VEzLQsqxxEhwO3nU')
.collection('friends')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((element) async {
print("hello " + element.id.toString());
await _userRef.doc(element.id).get().then((value) {
print("lalala" + value.data().toString());
info.add(value.data());
});
});
});
print(info.toString());
}
I am trying to build a Flutter application using Firestore.My firestore has two collections namely users and friends.Collection users contains documents with locations,names and Collection friends contains documents which each have a subcollection friends that store the Unique IDs of "users" who are friends. This is the output when I execute the above function
I/flutter ( 7773): hello eyHBWGrNoxSMe8cQUqWC
I/flutter ( 7773): []
I/flutter ( 7773): lalala{loc: Instance of 'GeoPoint', dname: hamza ansari}
PROBLEM: The data is not getting stored into the list 'info'. Any help with this would be appreciated :D
.Here is a photo of the friends collection.
And here is a photo of the users collection.
Would really love it if someone could help me out here :)
You can access the documents by snapshot.data.documents then you can get document Id like this
var doc= snapshot.data.documents;
var docId=doc[index].documentID
FirebaseFirestore.instance
.collection('dishes')
.doc(docId)
.collection('ingredients')
.snapshots(),
i think the problem is that you are simply not returning anything in your Future.
try this
FirebaseFirestore _firestore = FirebaseFirestore.instance;
CollectionReference _userRef = FirebaseFirestore.instance.collection('users');
Future getFriends() async {
List<Map> info = [];
await _firestore
.collection('friends')
.doc('lUb3VEzLQsqxxEhwO3nU')
.collection('friends')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((element) async {
print("hello " + element.id.toString());
await _userRef.doc(element.id).get().then((value) {
print("lalala" + value.data().toString());
info.add(value.data());
});
});
});
return info ;
}
The problem seems to be with the conversion of the subcollection to a list. Try the following:
FirebaseFirestore _firestore = FirebaseFirestore.instance;
CollectionReference _userRef = FirebaseFirestore.instance.collection('users');
Future getFriends() async {
List<Map> info = [];
await _firestore
.collection('friends')
.doc('lUb3VEzLQsqxxEhwO3nU')
.collection('friends')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((element) async {
print("hello " + element.id.toString());
await _userRef.doc(element.id).get().then((value) {
print("lalala" + value.data().toString());
info.add(Map(Map.fromMap(value.data())));
});
});
});
print(info.toString());
}

Comparing elements Flutter/FirebaseFirestore

i have a problem with getting users, whose emails are in the other user's array 'SeniorList'. It prints me empty array when i have a user with an email from
_seniorList
I'm new to a Firebase so every advice is important.
Here is Firestore DB structure:
https://imgur.com/yrtJ4RZ
https://imgur.com/z3gurUq
And Code i tried:
Future<List<String>> getSeniorList() async {
var _currentUser = FirebaseAuth.instance.currentUser;
List<String> list;
DocumentSnapshot data = await FirebaseFirestore.instance
.collection('users')
.doc(_currentUser!.uid)
.get();
list = List.from(data['SeniorList']);
return list;
}
Future<void> printSeniorNameList() async {
final List<String> _seniorList = await getSeniorList();
print(_seniorList);
final QuerySnapshot result = await FirebaseFirestore.instance
.collection('users')
.where('email', arrayContainsAny: _seniorList)
.get();
final List<DocumentSnapshot> documents = result.docs;
print(documents);
}
PS. If u can tell me how to paste Images in a right way i will be thanksfull!
Solved it this way:
Future<List<String>> getSeniorList() async {
var _currentUser = FirebaseAuth.instance.currentUser;
List<String> list;
DocumentSnapshot data = await FirebaseFirestore.instance
.collection('users')
.doc(_currentUser!.uid)
.get();
list = List.from(data['SeniorList']);
return list;
}
Future<bool> isSeniorAlreadyInTheList(String checkemail) async {
final List<String> _seniorList = await getSeniorList();
if (_seniorList.contains(checkemail)) {
return true;
} else {
print('Email not in a Senior List');
return false;
}
}
Future<void> printSeniorNameWhoseEmailInTheList(String checkemail) async {
bool exists = await isSeniorAlreadyInTheList(checkemail);
Map<String, dynamic>? seniorName;
if (exists) {
var result = await FirebaseFirestore.instance
.collection('users')
.where('email', isEqualTo: checkemail)
.limit(1)
.get();
seniorName = result.docs[0].data();
print(seniorName!['username']);
} else
print('That users email is not in a SeniorList!');
}
Already Works for me.

Flutter firestore save id to list

how can I save all document Ids From firestore inside a list?
Thats what I tried but I couldn't manage to only save the ID:
List ticketIds = [];
getTicketIds() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
ticketIds = await FirebaseFirestore.instance
.collection("users")
.doc(prefs.getString("userId"))
.collection("tickets")
.get()
.then((val) => val.docs);
Hello you need to loop trough the docs and you can retreive the docs id, here is the code :
Future<List<String>> getTicketIds() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
List<String> ticketIds = await FirebaseFirestore.instance
.collection("users")
.doc(prefs.getString("userId"))
.collection("tickets")
.get()
.then((val) {
List<String> idOfDocuments = [];
val.docs.forEach((element) {
idOfDocuments.add(element.id);
});
return idOfDocuments;
});
return ticketIds;
}

Function returning null in FLutter

I am trying to implement the function below but it gives me null.
To be specific, Future credit() is not updating the variable value. There is no problem with the database because if I put print(doc['value']) instead of value += doc['value'], I get the expected result.
It seems, getCredit() is the one returning null.
Future credit() async {
final FirebaseUser user = await FirebaseAuth.instance.currentUser();
final String uid = user.uid;
int value = 0;
Firestore.instance
.collection('entries')
.where("uid", isEqualTo: uid)
.where("type", isEqualTo: "+")
.orderBy("time", descending: true)
.snapshots()
.listen((data) => data.documents.forEach((doc) => value += doc['value']));
print(value); // doesnt update value
return value;
}
int getCredit() {
credit().then((value) {print(value);});
credit().then((value) {return value;}); // return mot working
}
Thanks!
try this:
Future<int> getCredit() async {
return await credit();
}
Fixed it. It seems it was a problem with the scope of variable.
int cr = 0;
Future credit() async {
final FirebaseUser user = await FirebaseAuth.instance.currentUser();
final String uid = user.uid;
Firestore.instance
.collection('entries')
.where("uid", isEqualTo: uid)
.where("type", isEqualTo: "+")
.orderBy("time", descending: true)
.snapshots()
.listen((data) => data.documents.forEach((doc) {cr = cr + doc['value'];}));
print('$cr');
}

Resources