how can I check if a doc in firebase exist? - firebase

Im trying to check if a document in my firebase console exist but I cannot use doc and dont know why . Maybe anyone can help heres my code
#override
void initState() {
super.initState();
getalldata();
}
getalldata() async {
//get videos as future
myVideos = FirebaseFirestore.instance
.collection('videos')
.where('uid', isEqualTo: widget.userid)
.get();
var documents = await FirebaseFirestore.instance
.collection('videos')
.where('uid', isEqualTo: widget.userid)
.get();
for (var item in documents.docs) {
likes = item.data()['likes'].length + likes;
}
setState(() {
dataisthere = true;
});
}
So in the documents var I wanna check if documents exists.
And them I wanna use the value inside an if else check

#override
void initState() {
super.initState();
getalldata();
}
getalldata() async {
//get videos as future
myVideos = await FirebaseFirestore.instance
.collection('videos')
.where('uid', isEqualTo: widget.userid)
.get();
var documents = await FirebaseFirestore.instance
.collection('videos')
.where('uid', isEqualTo: widget.userid)
.get();
if(documents.docs.isNotEmpty){
for (var item in documents.docs) {
likes = item.data()['likes'].length + likes;
}
setState(() {
dataisthere = true;
});
} else{
setState(() {
dataisthere = false;
});
}
}

Related

Flutter firebase firestore combine 2 query

In the example below, I want to combine 2 firestore queries, but I could not get it to work.
final List<Who> pagedData =
await _query.get().then((QuerySnapshot snapshot) async {
if (snapshot.docs.isNotEmpty) {
_lastDocument = snapshot.docs.last;
} else {
_lastDocument = null;
}
return snapshot.docs.map((QueryDocumentSnapshot e) async {
final data = e.data() as Map<String, dynamic>;
Whoes w = Whoes.fromMap(e.data());
User u = await _firestore
.collection("user")
.doc(data['s'])
.get()
.then((DocumentSnapshot documentSnapshot) => User.fromMap(
documentSnapshot.data()));
return Who(w, u);
}).toList();
});
When I put await in the user part, things get confused and I couldn't edit it.
What I want to output as a result is List<Who>
What am I missing?
It gives me this error:
The return type 'List<Future<Who>>' isn't a 'Future<List<Who>>', as required by the closure's context.
I solved the problem, I leave it here for anyone who encounters this
final List<Who> pagedData =
await _query.get().then((QuerySnapshot snapshot) async {
if (snapshot.docs.isNotEmpty) {
_lastDocument = snapshot.docs.last;
} else {
_lastDocument = null;
}
Iterable<Future<Who>> futureWho =
snapshot.docs.map((QueryDocumentSnapshot e) async {
final data = e.data() as Map<String, dynamic>;
Whoes w = Whoes.fromMap(e.data());
User u = await _firestore
.collection("user")
.doc(data['s'])
.get()
.then((DocumentSnapshot documentSnapshot) => User.fromMap(
documentSnapshot.data()));
return Who(w, u);
});
Future<List<Who>> listWho = Future.wait(futureWho);
return listWho;
});

Use local variable outside the function with dart

i want to use "docid" outside the function how to do it ?
getC() async {
Usersref.where("email", isEqualTo: widget.list['email'])
.get()
.then((QuerySnapshot snapshot) {
snapshot.docs.forEach((document) {
print(document.id);
final docid = document.id;
});
});
}
Future<List<String>>getC() async {
List<String> idList=[];
await Usersref.where("email", isEqualTo: widget.list['email'])
.get()
.then((QuerySnapshot snapshot) {
snapshot.docs.forEach((document) {
print(document.id);
idList.add( document.id);
});
});
return idList;
}

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.

How can I check this in collection?

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"]);
});

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