Flutter firestore append another QuerySnapshot - flutter

how do I append another QuerySnapshot to a QuerySnapshot?
static final CollectionReference _col = FirebaseFirestore.instance.collection('post');
Stream<QuerySnapshot<Object?>> query = _col.where('firstReleaseDate', isLessThanOrEqualTo: Timestamp.now()).snapshots();
QuerySnapshot ss = await _col
.query() <-----append here
.orderBy(field, descending: isDescending)
.startAfterDocument(lastDoc)
.limit(limit)
.get()
.timeout(TIMEOUT_DURATION);

Related

Flutter retrieve all documents in the sub-sub-Collection in firebase

my nested collections looks like this:
User--> drugs--> drugsTime
I want to retrieve all the documents in the subsub-collection (drugsTime) for specific drug however I dont know the drug document id so I did the following :
getData() async {
final User? user = FirebaseAuth.instance.currentUser;
final _uid = user?.uid;
var drugID = "";
final QuerySnapshot<Map<String, dynamic>> querySnapshot =
await FirebaseFirestore.instance
.collection("users")
.doc(_uid)
.collection('drug')
.where("drugName", isEqualTo: widget.title)
.get();
querySnapshot.docs.forEach((element) async {
drugID = element.id;
});
final QuerySnapshot<Map<String, dynamic>> querySnapshot2 = (await FirebaseFirestore.instance
.collection("users")
.doc(_uid)
.collection("drug")
.doc(drugID)
.get()) as QuerySnapshot<Map<String, dynamic>>;
querySnapshot2.docs.forEach((element) async {
drugTime .add (element.get('time'));
isTaken.add(element.get("isTaken"));
});
print(drugTime);
print(isTaken);
}
but this error ocurr:
E/flutter (24517): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type '_JsonDocumentSnapshot' is not a subtype of type 'QuerySnapshot<Map<String, dynamic>>' in type cast
E/flutter (24517): #0 _historyState.getData (package:taafi_application_v1/pages/history.dart:38:17)
E/flutter (24517): <asynchronous suspension>
the problem shows in
as QuerySnapshot<Map<String, dynamic>>;
how can i solve it ?
Here, you casted DocumentSnapshot with QuerySnapshot, where will return QuerySnapshot and doc will return DocumentSnapshot.
Your code of method getData should be as following
getData() async {
final User? user = FirebaseAuth.instance.currentUser;
final _uid = user?.uid;
var drugID = "";
final QuerySnapshot<Map<String, dynamic>> querySnapshot =
await FirebaseFirestore.instance
.collection("users")
.doc(_uid)
.collection('drug')
.where("drugName", isEqualTo: widget.title)
.get();
querySnapshot.docs.forEach((element) async {
drugID = element.id;
});
final DocumentSnapshot<Map<String, dynamic>> doc = await FirebaseFirestore.instance
.collection("users")
.doc(_uid)
.collection("drug")
.doc(drugID)
.get();
drugTime.add (doc.data()!['time']);//Make sure time has value
isTaken.add(doc.data()!['isTaken']);
print(drugTime);
print(isTaken);
}
Please make sure of which you are requested for.

How to iterate and sum value of data coming from firestore with flutter

I have a function to retrieve data from firebase as follows,
getTrips() async {
var data = await FirebaseFirestore.instance
.collection('trips')
.orderBy('date')
.where('date', isGreaterThan: DateTime.now())
// .where('date', isGreaterThan: DateTime.parse(widget.searchTrip.date))
.get();
setState(() {
_allTrips = data.docs;
});
return data.docs;
}
I want to iterate the List _allTrips or data.docs and get sum of values in the field 'seats' which is int values on the collection being retrieved by abpve code. How can I achieve this?
add a .then() after the .get() and do the following:
var data = await FirebaseFirestore.instance
.collection('trips')
.orderBy('date')
.where('date', isGreaterThan: DateTime.now())
// .where('date', isGreaterThan: DateTime.parse(widget.searchTrip.date))
.get()
.then((snapshot){
_allTrips = snapshot.docs;
_allTrips.forEach((element)=> totalNumber+=element.data()['seats'])
};

async function not completing when querying FirebaseFirestore

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.

How to sum all discounts collection and then get sum of these value for all students in another collection

When i test this code to get list for allDiscountForAllStudents, i got an empty list. Why is that?
this is code
getAllDiscountForAllStudents() async {
int _allDiscountForAllStudents = 0;
QuerySnapshot querySnapshot = await FirebaseFirestore.instance
.collection('courses')
.doc(_id2)
.collection('course_students')
.where('withdraw', isEqualTo: false)
.get();
List allCourseStudents = querySnapshot.docs.toList();
QuerySnapshot snapshot2;
for (int i = 0; i < allCourseStudents.length; i++) {
snapshot2 = await FirebaseFirestore.instance
.collection('discounts')
.where('Course Id', isEqualTo: _id2)
.where('User Id', isEqualTo: allCourseStudents[i]['ID'])
.where('Approved', isEqualTo: true)
.get();
}
List allDiscountForAllStudents = snapshot2.docs.toList();
print(allDiscountForAllStudents);
return _allDiscountForAllStudents;
}
It looks like you override the total list with the data of the last student you get and if that one has no data it will be empty. Could you try it with this code:
getAllDiscountForAllStudents() async {
int _allDiscountForAllStudents = 0;
QuerySnapshot querySnapshot = await FirebaseFirestore.instance
.collection('courses')
.doc(_id2)
.collection('course_students')
.where('withdraw', isEqualTo: false)
.get();
List allCourseStudents = querySnapshot.docs.toList();
List allDiscountForAllStudents=[];
for (int i = 0; i < allCourseStudents.length; i++) {
QuerySnapshot snapshot2;
snapshot2 = await FirebaseFirestore.instance
.collection('discounts')
.where('Course Id', isEqualTo: _id2)
.where('User Id', isEqualTo: allCourseStudents[i]['ID'])
.where('Approved', isEqualTo: true)
.get();
allDiscountForAllStudents.addAll(snapshot2.docs.toList());
}
print(allDiscountForAllStudents);
return _allDiscountForAllStudents;
}

How to check if subcollection exists in Firestore with Flutter future<bool>

I have a problem with return true/false statement from Firestore query if some sub-collection exists.
Here is my code:
Future<bool> checkIfCollectionExist(
String collectionName, String productId) async {
await _db
.collection('products')
.doc(productId)
.collection(collectionName)
.limit(1)
.get()
.then((value) {
return value.docs.isNotEmpty;
});
}
As a result I get Instance of Future<bool>, but I need true/false answer.
What I doing wrong here ?
Use
Future<bool> checkIfCollectionExist(String collectionName, String productId) async {
var value = await _db
.collection('products')
.doc(productId)
.collection(collectionName)
.limit(1)
.get();
return value.docs.isNotEmpty;
}
Or
Future<bool> checkIfCollectionExist(String collectionName, String productId) {
return _db
.collection('products')
.doc(productId)
.collection(collectionName)
.limit(1)
.get()
.then((value) {
return value.docs.isNotEmpty;
});
}