I fetching data from firebase performing a query and updating a bool based on the query. But my code doesn't work. I tried printing the snapshots but I get "Instance of '_ControllerStream<QuerySnapshot<Map<String, dynamic>>>'" in the terminal how do I solve this.
Stream<QuerySnapshot<Map<String, dynamic>>>namees = await FirebaseFirestore
.instance
.collection('lender')
.doc(auth.currentUser!.email)
.collection('borrowers')
.where('Name', isEqualTo: textfieldname).snapshots();
print(namees);
if (namees.isEmpty == true) {
setState(() {
isThere = true;
});
} else {
setState(() {
isThere = false;
});
}
Related
I am trying to achieve a task in which I have a List<dynamic>and its giving me multiple values on its indexes e.g. ['Me','Admin', so on....] something like this.
I cannot pass the List directly to Document ID it gives index error and I don't if it will still give error or not If the List give data in string List<String>
I want to loop around the indexes of this list and pass it to Firebase collection's document id to get multiple data's of the users. For example on list's index 0 there's Me coming for myself and on index 1 there's Admin coming. Both have their respective data stored in Firestore collection with their own document id's Me and Admin. I want it to be checked on the runtime the app will check if its Me or Admin or Some other index value
Here's my code of the list and the firestore I'm trying to achieve.
List<dynamic> clientcodes = [];
void getclientcodes() async {
final clientcode = await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser!.email)
.get()
.then((clientcode) {
return clientcode.data()!["clientcode"];
});
setState(() {
if (clientcode != null) {
clientcodes = clientcode;
} else if (clientcode == null) {
setState(() {
const SpinKitSpinningLines(size: 100, color: Color(0xFF25315B));
});
}
});
}
Firestore:
Future getdatastatus() async {
DocumentSnapshot result = await FirebaseFirestore.instance
.collection("Statements")
// .doc("If I hardcode it the value of index 0 or 1 it works fine")
.doc(portfolionames.toString()) // This is area of issue
.get();
if (result.exists) {
print("Yes");
} else {
print("No");
}
}
You can insert getdatastatus() inside a loop, and let it get the index automatically by comparing it with any value you want it, see this:
Future getdatastatus() async {
for (var item in clientcodes) {
String docId = item.id;
if (docId == 'X' || docId == 'Y') {
DocumentSnapshot result = await FirebaseFirestore.instance
.collection("Statements")
.doc(docId)
.get();
if (result.exists) {
print("Yes");
} else {
print("No");
}
}
}
}
Hope that work with you!!
Update
In the first section of your code, I think there is a problem..
You can create the list out of the firestore streaming, then add the coming data to the list of model, after that you can loop it to take the value you want.
Class Database{
List<TestModel> clientcodes = [];
getclientcodes() {
return FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser!.email)
.snapshots()
.listen((event) {
clientcodes.add(TestModel.fromMap(event));
setState(() {
if (clientcode != null) {
clientcodes = clientcode;
} else if (clientcode == null) {
setState(() {
const SpinKitSpinningLines(size: 100, color: Color(0xFF25315B));
});
}
});
});
}
}
class TestModel {
late String name;
late String description;
TestModel({
required this.name,
required this.description,
});
TestModel.fromMap(DocumentSnapshot data) {
name = data['name'];
description = data['description'];
}
}
See the print statement down below. It never executes.
Future<void> populate() async {
final userId = FirebaseAuth.instance.currentUser!.uid;
final db = FirebaseFirestore.instance;
// Get list of ids of parties use swiped on.
var snapshot1 = await db
.collection("partiers_swipes")
.where('userId', isEqualTo: userId)
.get();
var partyIdsUserSwipesOn = [];
if (snapshot1.size > 0) {
snapshot1.docs.forEach((element) {
partyIdsUserSwipesOn.add(element.data()['partyId']);
});
}
var snapshot2 = await db
.collection("parties")
.where(FieldPath.documentId, whereNotIn: partyIdsUserSwipesOn)
.get();
print('This never executes');
}
The whereNotIn argument is not supported by the where clause. This crashes the function.
bool hasMore = true;
bool isLoading = false;
DocumentSnapshot nextDocument;
DocumentSnapshot previousDocument;
getProducts() async {
if (!hasMore) {
print('No More Products');
return;
}
if (isLoading) {
return;
}
setState(() {
isLoading = true;
});
QuerySnapshot querySnapshot;
if (nextDocument == null) { // First time to get products
querySnapshot = await firestore
.collection('products')
.orderBy('name')
.limit(10)
.getDocuments();
} else {
querySnapshot = await firestore
.collection('products')
.orderBy('name')
.startAfterDocument(nextDocument)
.limit(10)
.getDocuments();
print(1);
}
if (querySnapshot.documents.length < 10) {
hasMore = false;
}
nextDocument = querySnapshot.documents[querySnapshot.documents.length - 1];
previousDocument = querySnapshot.documents[querySnapshot.documents.length - 19];
products.addAll(querySnapshot.documents);
setState(() {
isLoading = false;
});
}
try to use this code i don't do this before but i just try to help youtry to use this code i don't do this before but i just try to help youtry to use this code i don't do this before but i just try to help youtry to use this code i don't do this before but i just try to help youtry to use this code i don't do this before but i just try to help youtry to use this code i don't do this before but i just try to help youtry to use this code i don't do this before but i just try to help you
trying to fetch results within a for loop , but for loop doesn't wait for firestore results.tried forEach as well before .
Future<bool> checkIfNewMessages() async{
bool hasNewMessage=false;
QuerySnapshot _myDoc = await Firestore.instance.collection('PropMap')
.orderBy('ProJoiningDate')
.where('TenId', isEqualTo: globals.memberAuthId)
.getDocuments();
List<DocumentSnapshot> properties = _myDoc.documents;
if(properties.length>0)
for(final property in properties) {
//properties.forEach((property) { //tried forEach() as well
String propid= property.data['PropertyId'];
if(property.data['LastVisitTime']!=null) {
DateTime tenantsLastPropVisitTime = property.data['LastVisitTime'].toDate();
getLastPropertyChatTime(propid).then((latestPropChatTime) { //This 'then' seems not working
print('LAST chat date is ${latestPropChatTime}');
if (latestPropChatTime.isAfter(tenantsLastPropVisitTime)) //This means he has not seen new messages , lets notify him
{
hasNewMessage= true;
}
});
}
};
return hasNewMessage;
}
And these are the fetch methods,when the breakpoint is at getDocuments() of getTheLastChat() the control just jumps back to for loop again without waiting for results .
Future getTheLastChat(propId) async {
QuerySnapshot _myDoc =await Firestore.instance.collection('Chats').orderBy('ChatDate', descending: true)
.where('PropertyId', isEqualTo: propId)
.limit(1)
.getDocuments();
List<DocumentSnapshot> tenants = _myDoc.documents;
return tenants;
}
Future<DateTime> getLastPropertyChatTime(propId) async {
DateTime lastChatTime= DateTime.now().add(Duration(days:-365));
var lastChatTimeDocs = await getTheLastChat(propId);
lastChatTime=lastChatTimeDocs.length>0?lastChatTimeDocs[0].data["ChatDate"].toDate():DateTime.now().add(Duration(days:-365));
return lastChatTime;
}
You can use the Future.forEach to achieve your requirement
Future<void> buildData(AsyncSnapshot snapshot) async {
await Future.forEach(snapshot.data.documents, (element) {
employees.add(Employee.fromSnapshot(element));
});
}
The following code works fine, because it return only a simple list, but in some cases that I need to do nested Firebase calls, I can't make things happen in the right order, and the main return statement comes incomplete. What can I do to improve my Future Asynchronous Calls?
Future<List<MyNotification>> getNotifications() async {
var uid = await FirebaseAuth.instance.currentUser();
List<MyNotification> tempNots = await Firestore.instance
.collection("notifications")
.where("targetUsers", arrayContains: uid.uid)
.getDocuments()
.then((x) {
List<MyNotification> tempTempNots = [];
if (x.documents.isNotEmpty) {
for (var not in x.documents) {
tempTempNots.add(MyNotification.fromMap(not));
}
}
return tempTempNots = [];
});
return tempNots;
}
The most important thing; don't use then inside your async functions. I modified your code like this;
Future<List<MyNotification>> getNotifications() async {
// Using the type definition is better.
FirebaseUser user = await FirebaseAuth.instance.currentUser();
// The return type of getDocuments is a QuerySnapshot
QuerySnapshot querySnapshot = await Firestore.instance
.collection("notifications")
.where("targetUsers", arrayContains: user.uid)
.getDocuments();
List<MyNotification> tempTempNots = [];
if (querySnapshot.documents.isNotEmpty) {
for (DocumentSnapshot not in querySnapshot.documents) {
tempTempNots.add(MyNotification.fromMap(not));
}
}
return tempTempNots;
}